在关闭之前写入不可见的文件; fflush(stdout)无效 [英] Write to file not visible before close; fflush(stdout) ineffective
问题描述
我在写入文件时遇到一些问题,同时在while循环中也有延迟.这是一个片段:
I'm having some issues with writing to a file whilst also having a delay in a while loop. Here's a snippet:
void main(int){
FILE * fp = NULL;
sprintf(filename, "log%i.msg", SET_ID);
fp = fopen(filename, "w+");
fprintf(fp, "File started\n");
while(1){
fprintf(fp, "%i %u %s\n", someInt, someUnsigned, someString);
fflush(stdout);
sleep(5); // Commenting out this line will work
}
fclose(fp);
return 1;
}
运行代码将使我得到一个0字节的输出文件,其中的任何内容在睡眠生效时都没有,尽管我的代码完成运行后该文件确实具有预期的内容.但是,当我删除sleep(5);
行时,它确实可以正确打印.我已经搜索过此内容,但是发现它需要刷新,但是我这样做了(尽管显然是错误的).我在做什么错了?
Running the code gives me an output file of 0 bytes with nothing in it whilst the sleep is taking effect, although the file does have the expected content when my code finishes running. However, when I remove the sleep(5);
line, it does print correctly. I've searched about this already, but what I've found is that it needs to be flushed, but I do this (though apparently incorrectly). What am I doing wrong?
推荐答案
您正在刷新标准输出.您需要刷新文件.
You're flushing stdout. You need to flush the file.
更改
fflush(stdout)
到
fflush(fp)
关于为何sleep()出现 影响文件中内容是否可见的原因:如果不存在该内容,则以更高的速率写入文件,因此填充内存缓冲区和刷新到磁盘要快得多.但是,如果您足够耐心,即使在sleep()存在的情况下,您也会在磁盘上看到内容.
In terms of why the sleep() appears to impact whether contents are visible in the file: Without it present, you're writing to the file at a much higher rate, so you fill the in-memory buffer and flush to disk much faster. If you were patient enough, though, you'd see contents on-disk even with the sleep() present.
这篇关于在关闭之前写入不可见的文件; fflush(stdout)无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!