You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现复制文件开头X字节并追加到末尾?附故障代码排查

问题分析与修复

你的代码逻辑完全不符合需求,核心错误在于读取和写入的位置、内容方向搞反了,导致文件内容没有变化甚至可能被破坏。以下是问题点和修复方案:

核心问题

  • 读取内容错误:需求是复制文件开头到x字节的内容,但你代码里是从copy_position(x或文件大小)开始读取到文件末尾的内容,这和需求完全相反。
  • 写入位置错误:你把读取的内容写回了copy_position位置,这是覆盖原文件内容,而不是追加到文件末尾。
  • 变量逻辑错误:copy_position的定义逻辑错误,应该是要复制的字节数copy_bytes = (x < file_size) ? x : file_size,而不是位置。

修复后的代码

#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);

    // 确定要复制的字节数:x不超过文件大小则复制x字节,否则复制全部
    long copy_bytes = (x < file_size) ? x : file_size;

    unsigned char buffer[1024];
    size_t bytes_read;

    // 移到文件开头,读取前copy_bytes字节
    fseek(file, 0, SEEK_SET);
    bytes_read = fread(buffer, 1, copy_bytes, file);
    if (bytes_read != copy_bytes) {
        perror("Error reading file");
        fclose(file);
        exit(EXIT_FAILURE);
    }

    // 移到文件末尾,写入读取的内容(追加)
    fseek(file, 0, SEEK_END);
    size_t bytes_written = fwrite(buffer, 1, bytes_read, file);
    if (bytes_written != bytes_read) {
        perror("Error writing file");
        fclose(file);
        exit(EXIT_FAILURE);
    }

    fclose(file);

    // 获取并输出inode和复制字节数
    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]);
    if (x <= 0) {
        fprintf(stderr, "Error: x must be a positive integer\n");
        return 115;
    }

    copy_file_fragment(x);

    return 0;
}

额外优化点

  • 增加了输入验证:确保x是正整数,符合需求里的“正整数x”要求。
  • 增加了读写操作的错误检查,避免读写失败时无提示。
  • 修正了变量命名,copy_bytes更准确表达要复制的字节数,而非位置。

内容的提问来源于stack exchange,提问作者Arnas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 12:45:05