Using fscanf and fprintf together in C

#include <stdio.h> #include <stdlib.h> #define FILE_NAME "ff.txt" int main() { char x[10],y[10]; FILE *fp; fp = fopen(FILE_NAME, "r+"); if (fp == NULL) { printf("couldn't find %s\n ",FILE_NAME); exit(EXIT_FAILURE); } fprintf(fp,"Hello2 World\n"); fflush(fp); fscanf(fp,"%s %s",x,y); printf("%s %s",x,y); fclose(fp); return 0; } 

Here is my version of what I'm trying to do. This code does not print anything in the console. If I delete the call to fprintf , it prints the first 2 lines in the file, for me it is Hello2 World . Why is this happening? Even after i fflush fp ?

+6
source share
1 answer

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); 
+6
source

All Articles