After fprintf()
the file pointer points to the end of the file. You can use fseek()
to set the pointer file at the beginning of the file:
fprintf(fp,"Hello2 World\n"); fflush(fp); fseek(fp, 0, SEEK_SET); fscanf(fp,"%s %s",x,y);
Or even better, as suggested by @Peter, use rewind()
:
rewind(fp);
rewind
:
Internal indicators of the end of the file and errors associated with the stream are cleared after a successful call to this function, and all effects from previous calls to ungetc in this stream.
In threads open for updating (read + write), a call to rewind allows switching between reading and writing.
It is always best to check the fscanf()
return code.
To avoid buffer overflows, you can use:
fscanf(fp,"%9s %9s",x,y);
source share