这是我的计划:
#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)
答案 0 :(得分:2)
问题是由于您的while
声明,您的程序不会关闭该文件。删除这些行:
while (1) {
};
如果意图是永远等待,则在执行fclose
语句之前使用while
关闭文件。
答案 1 :(得分:2)
使用FILE
指针的IO函数将要写入的数据缓存在程序内存中的内部缓冲区中,直到它们决定执行系统调用“真正”写入它(这通常用于普通文件)缓存的数据大小达到BUFSIZ
)。
在那之前,没有办法从程序之外强制写作。