繁体   English   中英

为什么使用fprintf文件流将数据写入未反映到文件

[英]Why is the data write not reflected to the file using fprintf file stream

这是我的程序:

#include <stdio.h>

int main() {
    FILE *logh;

    logh = fopen("/home/user1/data.txt", "a+");

    if (logh == NULL)
    {
        printf("error creating file \n");
        return -1;
    }

    // write some data to the log handle and check if it gets written..
    int result = fprintf(logh, "this is some test data \n");
    if (result > 0)
        printf("write successful \n");
    else
        printf("couldn't write the data to filesystem \n");

    while (1) {
    };

    fclose(logh);
    return 0;
}

当我运行该程序时,我看到正在创建文件,但它不包含任何数据。 我的理解是,在将数据实际写入文件系统之前,内存中已经有数据缓存,以避免多个IO提高性能。 而且我也知道我可以在程序内部调用fsync / fdatasync来强制同步。 但是我可以在不更改程序的情况下从外部强制进行同步吗?

我尝试从Linux shell运行sync命令,但是它不会使数据显示在文件中。 :(

如果有人知道其他替代方法,请提供帮助。

一个有用的信息:我对此进行了进一步研究,最终发现,要完全删除内部缓冲,可以使用int setvbuf(FILE *stream, char *buf, int mode, size_t size)FILE模式设置为_IONBF

问题是由于您的while语句,您的程序无法关闭文件。 删除这些行:

while (1) {
    };

如果打算永远等待,则在执行while语句之前,先用fclose关闭文件。

IO函数使用FILE指针将要写入的数据缓存在程序内存中的内部缓冲区中,直到他们决定执行系统调用以“真正”写入它为止(这通常用于普通文件,通常是在缓存的数据大小达到BUFSIZ )。 在此之前,还没有办法从程序外部强制进行书写。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM