如何从文件开头复制x个字节并将它们附加到文件末尾以使文件增加x个字节?

问题描述 投票:0回答:1

这是我的参数:

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;
}
c
1个回答
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

手动执行此操作,比您自己制作更简单。

  1. 打开 r+ 的文件
  2. 读取 X 字节。
  3. 寻求到底。
  4. 写入X字节。
    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);

补充说明:

  • 因为您使用的是固定缓冲区,所以请检查 x 是否大于您的缓冲区。
  • 每个文件操作都应该检查,但一定要执行 fseek,否则你会覆盖该文件。
© www.soinside.com 2019 - 2024. All rights reserved.