【问题标题】:file read from and file written to are not same读取的文件和写入的文件不相同
【发布时间】:2012-04-13 14:19:04
【问题描述】:

我正在尝试将大约 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 之后的 fflush 会为我这样做吗?

【问题讨论】:

    标签: c fflush


    【解决方案1】:

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

    【讨论】:

    • 你的意思是说 fwrite 没有 fflush 或 fclose 总是不可靠的?
    • fwrite() 是可靠的,但默认情况下会涉及缓冲,以提高绝大多数程序使用的整体效率。如果你正在做的事情不需要缓冲,你可以在打开文件后在文件上使用setbuf()来禁用缓冲。
    • @ajaybidari:请注意,如果进程干净退出(通过从main() 返回或调用exit()),所有打开的带有未写入缓冲数据的流都会被刷新,所有打开的流都会被关闭。请注意,即使使用fflush() 或fclose(),写入操作也可能会被操作系统缓冲,因此在系统崩溃后如果不调用某些特定于操作系统的同步函数,它们可能无法持久。
    【解决方案2】:

    不保证fread 会给你所有你要求的字节。它可以给你更少,这就是返回码的用途。

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

    返回码的检查也延伸到fopen 调用 - 不能保证打开会起作用。

    例如,下面的完整程序将尝试将最多 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;
    }
    

    【讨论】:

    • fread() only 如果发生错误或到达文件末尾,则返回一个简短的项目计数。重试fread() 没有意义 - 如果到达文件末尾,则没有更多数据;如果发生错误,文件位置指示符的值是不确定的。这与典型的底层低级函数(如 read())形成对比,后者可以返回短读取而不会出错。
    猜你喜欢
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    相关资源
    最近更新 更多