这是我的参数:
1:我接受一个命令行作为参数 - 一个正整数 x。 如果给出的参数数量无效,则程序必须以错误代码 115 结束
2:我将文件text1.txt的片段从文件开头复制到x字节到同一个文件的末尾,即文件必须增加X字节
3:如果X大于文件大小,则程序必须仅复制原始文件中的数据,并从指定位置X开始写入它们
4:程序必须输出文件text1.txt,其中包含i节点号和复制的字节数
总体思路是,如果我的text1.txt文件是这样的: 1/2+23asd 我选择复制 3 个字节,启动程序后 text1.txt 文件应如下所示: 1/2+23asd1/2
这是我的尝试,但我似乎无法让它工作:启动之后和之前,text1.txt 保持不变
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
void copy_file_fragment(int x) {
FILE *file = fopen("text1.txt", "r+b");
if (file == NULL) {
perror("Error opening file");
exit(EXIT_FAILURE);
}
fseek(file, 0, SEEK_END);
long file_size = ftell(file);
long copy_position = (x < file_size) ? x : file_size;
unsigned char buffer[1024];
size_t bytes_read;
fseek(file, copy_position, SEEK_SET);
bytes_read = fread(buffer, 1, file_size - copy_position, file);
fseek(file, copy_position, SEEK_SET);
fwrite(buffer, 1, bytes_read, file);
fclose(file);
struct stat st;
if (stat("text1.txt", &st) == -1) {
perror("Error getting file information");
exit(EXIT_FAILURE);
}
printf("Inode Number: %ld\n", st.st_ino);
printf("Copied Byte Number: %zu\n", bytes_read);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <x>\n", argv[0]);
return 115;
}
int x = atoi(argv[1]);
copy_file_fragment(x);
return 0;
}
如果这是一个实际问题,shell 实用程序
head
、>>
(追加)、cat
和 stat
可以完成您想要的操作。下面将从 test.txt 的顶部到末尾追加 5 个字节,打印 test.txt 及其 inode。
head -c5 test.txt >> test.txt
cat test.txt
stat --format '%i' test.txt
手动执行此操作,比您自己制作更简单。
FILE *file = fopen(Filename, "r+b");
if (file == NULL)
{
perror("Error opening file");
exit(EXIT_FAILURE);
}
unsigned char buffer[1024];
size_t bytes_read = fread(buffer, 1, x, file);
fseek(file, 0, SEEK_END);
fwrite(buffer, 1, bytes_read, file);
fclose(file);
补充说明: