fprintf function not working but it returns positive number

浪尽此生 提交于 2019-12-25 05:07:26

问题


I'm using fprintf in the following way. Everything seems to be ok but fprintf doesn't print to my file at all!

fprintf(pFile, "%s\n", "print");

Something that is strange is that fprintf returns OK. it returns 6 in the above code, but not printing to file!

The file is created successfully but is empty.

changing it to printf is printing and OK too.


回答1:


fprintf and the other stdio output functions are buffered, which means that the output is first stored in memory, and not actually printed until later. When printing to the screen using standard output, each new line flushes the buffer, so with printf you would see the output immediately, but when printing to a file the buffer won't be flushed until you have written (for example) 4096 bytes. You can add fflush(pFile); to flush the buffer, if you for some reason need the output to appear on the file quickly.

The buffer is also flushed when calling fclose, or closing the file implicitly by properly exiting the program, but if the program keeps running without closing the file, or if it crashes, you will need fflush to see the output on the file.



来源:https://stackoverflow.com/questions/19587210/fprintf-function-not-working-but-it-returns-positive-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!