审查生成的文件复制

来自 C 文件 I/O
C23 (GCC 13.3.0) 高级 12分钟 找出 5处问题

审查这个用于复制任意文件的生成函数。

把任意字节从已有源文件复制到新建目标,不得替换已有目标;处理短传输和所有 I/O 错误,并且只在关闭成功后报告成功。

C
#include <stdio.h>

int copy_file(const char *source_path, const char *destination_path) {
    FILE *source = fopen(source_path, "r");
    if (source == NULL) {
        return -1;
    }

    FILE *destination = fopen(destination_path, "wb");
    unsigned char buffer[4096];

    while (!feof(source)) {
        size_t count = fread(buffer, 1, sizeof buffer, source);
        (void)count;
        fwrite(buffer, sizeof buffer, 1, destination);
        fflush(destination);
    }

    fclose(source);
    fclose(destination);
    return 0;
}

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误