I watched SO post fseek does not work when the file is opened in "a" (append) , and I have doubts about the initial value of the file pointer returned by ftell () when we open the file in "a" mode. I tried under the code with the file1.txt file containing the "Hello welcome" data and printed the position of the pointer in different places. Ftell () will initially return position 0. After adding ftell () will return the last position. If we do fseek (), the file pointer will change, in which case I will return to 0 position. In add mode, we cannot read data. Why is the pointer in its original position? Also is there any use of fseek in add mode?
#include<stdio.h>
#include <string.h>
#include <errno.h>
#define MAX_BUF_SIZE 50
void readString(char* buffer,int maxSize)
{
fgets(buffer,maxSize,stdin);
strtok(buffer,"\n");
}
extern int errno;
int main()
{
FILE *fp1;
char data[50];
fp1=fopen("file1.txt","a");
if(fp1==NULL)
{
fprintf(stderr,"%s\n",strerror(errno));
}
printf("Initial File pointer position in \"a\" mode = %ld\n",ftell(fp1));
printf("\nEnter some data to be written to the file\n");
readString(data,MAX_BUF_SIZE);
fputs(data,fp1);
printf("File pointer position after write operation in append mode = %ld\n",ftell(fp1));
fseek(fp1,0,SEEK_SET);
printf("File pointer position after fseek in append mode = %ld\n",ftell(fp1));
return(0);
}
source
share