为什么数据写入没有使用fprintf文件流反映到文件中

时间:2014-02-27 17:30:27

标签: c linux filesystems

这是我的计划:

#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命令,但它不会使数据出现在文件中。 :(

如果有人知道做同样的事情,请提供帮助。

一个有用的信息:我正在研究更多内容并最终发现这一点,为了完全删除内部缓冲,可以使用FILE_IONBF模式设置为int setvbuf(FILE *stream, char *buf, int mode, size_t size)

2 个答案:

答案 0 :(得分:2)

问题是由于您的while声明,您的程序不会关闭该文件。删除这些行:

while (1) {
    };

如果意图是永远等待,则在执行fclose语句之前使用while关闭文件。

答案 1 :(得分:2)

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