#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's a boiled down version of what I am trying to do. This code doesn't print anything in the console. If I remove the fprintf
call, it prints the first 2 strings in the file, for me its Hello2 World
. Why is this happening? Even after I fflush
the fp
?
fprintf () function writes formatted data to a file. fscanf () function reads formatted data from a file. fputchar () function writes a character onto the output screen from keyboard input.
C language provides two functions fprintf() and fscanf() for handling a set of mixed data values. The function fprintf() is used to write a mix of different data items into a specified file.
After fprintf()
, the file pointer points to the end of the file. You can use fseek()
to set the filepointer at the start 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
:The end-of-file and error internal indicators associated to the stream are cleared after a successful call to this function, and all effects from previous calls to ungetc on this stream are dropped.
On streams open for update (read+write), a call to rewind allows to switch between reading and writing.
It is always best to check the return code of fscanf()
too.
To avoid buffer overflow, you can use:
fscanf(fp,"%9s %9s",x,y);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With