I have a file named datafile.txt which contains
Line 1 here
Line 2 here
I want to store the first line in a character array and then replace the first charecter of the second line by 't' so I wrote the following code for this:
#include <stdio.h>
int main(){
FILE *fp=fopen("datafile.txt","r+");
char line[100];
fgets(line,100,fp);
printf("The position of file pointer is %d",ftell(fp));
fprintf(fp,"t");
fclose(fp);
}
The output is
The position of file pointer is 13
The problem here is that the fprintf is not working in this case i.e. I have tested the return value of fprintf which comes out to be 1 which means that fprintf is working but when I open the datafile.txt file then I can see that the first character of second line has not been replaced by 't' .If I add a fseek statement like this then it works:
#include <stdio.h>
int main(){
FILE *fp=fopen("datafile.txt","r+");
char line[100];
fgets(line,100,fp);
fseek(fp,ftell(fp),SEEK_SET);
printf("The position of file pointer is %d",ftell(fp));
fprintf(fp,"t");
fclose(fp);
}
The output on screen is the same as in the last case but in this case the first character of line 2 is replaced by 't'.
Can someone please explain me why this is not working in the first case but after adding the fseek statement it works. The position of file pointer is same in both the cases then too in first case it is not working.