This is more like a self reminder, since I spent hours fighting with such a simple issue…
Yesterday I was writing some C code that had to add some content to a file, pass that file to another program, then modify this same file a bit more and save it. Something very simple, like:
nstruc->fp = fopen(nstruc->file, "w+");
if(!nstruc->fp)
{
p_error("Unable to open %s", nstruc->file);
return(0);
}
write2fp(nstruc->fp);
send_file_to_externalprocess(nstruc->file);
writemore2fp(nstruc->fp);
fclose(nstruc->fp);
The problem is that when sending that file to the external process (exec), the file was always empty. “What is going on??”, I thought… After adding a bunch of debug statements, cursing a bit, I finally remembered:
I FORGOT TO FFLUSH!
For those not familiar with C, when you write something to stdout (or any file descriptor), the output is not written immediately, but it is buffered internally and only written when the internal buffer is full, the file is closed or you call fflush. So, the next time you can’t find out why a file is not being written, check if you called fflush. The fixed code looked like this:
nstruc->fp = fopen(nstruc->file, "w+");
if(!nstruc->fp)
{
p_error("Unable to open %s", nstruc->file);
return(0);
}
write2fp(nstruc->fp);
fflush(nstruc->fp);
send_file_to_externalprocess(nstruc->file);
..