读取的文件和写入的文件不相同

时间:2012-04-13 05:50:13

标签: c fflush

我试图将一个大约3KB的文件的内容读入缓冲区,然后将缓冲区的内容写入另一个文件。写入数据的文件仅包含写入其中的一部分数据。它的大小约为1KB。如何写剩下的数据?

fp1 = fopen("a.txt","rb");
fp2 = fopen("b.txt","wb");

fread(buffer, 1, BUFFER_SIZE,fp1);//reading from file pointed to by fp1
//BUFFER_SIZE = 3KB
fwrite(buffer, 1, BUFFER_SIZE, fp2);//writing into a file pointed to by fp2

fwrite之后会为我做这个吗?

2 个答案:

答案 0 :(得分:3)

fflush(fp2)fclose(fp2)会将待处理的缓冲字节移动到磁盘。

答案 1 :(得分:0)

没有保证fread将为您提供所要求的所有字节。它可以给你更少,这是返回代码的用途。

您需要使用返回代码来确定要发送给fwrite的信息量。

并且返回代码的检查也延伸到fopen调用 - 不能保证open会起作用。

举例来说,以下完整程序将尝试从一个文件复制到另一个文件3K:

#include <stdio.h>
#include <errno.h>

int main (void) {
    FILE *fp1, *fp2;
    char buff[3*1024];
    int bytesRead;

    // Open both files.

    if ((fp1 = fopen ("a.txt", "r")) == NULL) {
        printf ("Error %d opening a.txt\n", errno);
        return 1;
    }
    if ((fp2 = fopen ("b.txt", "w")) == NULL) {
        printf ("Error %d opening b.txt\n", errno);
        fclose (fp1);
        return 1;
    }

    // Transfer only up to buffer size.

    if ((bytesRead = fread (buff, 1, sizeof (buff), fp1)) == 0) {
        // Check error case.

        if (ferror (fp1)) {
            printf ("Error reading a.txt\n");
            fclose (fp1);
            fclose (fp2);
            return 1;
        }
    }

    // Attempt transfer to destination file.

    if (fwrite (buff, 1, bytesRead, fp2) != bytesRead) {
        printf ("Error writing b.txt\n");
        fclose (fp1);
        fclose (fp2);
        return 1;
    }

    // Close all files to finish up.

    fclose (fp1);
    fclose (fp2);
    return 0;
}