I have a function which writes binary data to a file or stdout
. However the call to fwrite()
sometimes fails, UNLESS I fflush(stderr)
or print a report to stderr
before attempting to fwrite
.
Is this normal behaviour, or indicative of some underlying memory problem? It's difficult to debug because as soon as I fprint
to stderr
the data I'm trying to fwrite
to stdout
, the "problem" disappears.
Here's a very simplified version of the function.
int writebinary(FILE *fpout, void *data, long ntowrite) {
long i;
/* lets say we know the input data is double float */
double *p = data;
/* including this test line makes the function work! */
for(i=0; i<ntowrite;i++) fprintf(stderr,"data[%d]=%g\n",i,p[i]);
/* attempt to write data[] as a single block of bytes */
m= fwrite(data,(size_t)(ntowrite*sizeof(double)),1,fpout);
if(m!=1) {
fprintf(stderr,"Write error: %d\n",ferror(fpout));
return(-1);
}
else return(m);
}
Any wisdom appreciated :)