使用fseek, read和fwrite来复制二进制文件



我想写一个函数,将覆盖二进制文件。现在我写了这个覆盖文本文件的函数,它工作得很好:

void myCopy(char source_file[50], char dest_file[50])
{
    FILE *fp1, *fp2;
    char a;
    fp1 = fopen(source_file, "rt");
    if (fp1 == NULL)
    {
        printf("Can't open this file, either it doesn't exist or doesn't contain anything.n");
    }
    fp2 = fopen(dest_file, "wt");
    if (fp2 == NULL)
    {
        printf("Can't open this file, either it doesn't exist or doesn't contain anything.n");
    }
    while ((a = fgetc(fp1)) != EOF)//While a failure did not accure.
    {
        fputc(a, fp2);
    }
    fclose(fp1);
    fclose(fp2);
}

我的问题是,是否有一种方法可以在不使用fputc, fgetc, fscanf和fprintf的情况下对所有二进制文件进行相同的操作?

如果您从fopen选项字符串中删除't'字符,您的代码将对二进制文件是正确的。但是您可以使用fread/fwrite函数和缓冲区来提高复制速度。例子:

const size_t buffer_size = 8192;
char buffer[buffer_size];
while (true) {
    size_t read = fread(buffer, sizeof(char), buffer_size, fp1);
    if (read > 0)
        fwrite(buffer, sizeof(char), buffer_size, fp2);
    else
        break;
}

相关内容

  • 没有找到相关文章

最新更新