Alonso Alonso - 3 years ago 123
C Question

How to make fprintf() writes immediately

One way to write into a file is by using

. However, this function does not write the results into a file immediately. It rather seems to write everything at once when the program is terminated or finished. My question is the following: I have a program that takes very long time to run (4-5 hours for big dataset). During this time, I want to see the intermediate results so that I don't have to wait for 5 hours. My university uses
Sun Grid Engine
for job submission. As most of you know, you have to wait until your job finishes to see your final results. Thus, I want to be able to write the intermediate results into text file and see the updated results as the program is processing (Similarly if I am using
). How can I modify
to write anything I want immediately to the target file ? Any idea is appreciated.

Thank you

Answer Source

You can use the fflush function after each write to flush the output buffer to disk.

fprintf(fileptr, "writing to file\n");

If you really want to be sure the file is written to disk, i.e. you want to flush the kernel buffers as well as the userspace buffers, also use fsync:


But fflush should be sufficient. Don't bother with fsync unless you find that you need to.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download