Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top