I was looking at SO post fseek does not work when file is opened in "a" (append) mode and I got a doubt regarding initial value of file pointer returned by ftell() when we open the file in "a" mode. I tried below code with file1.txt containing data "Hello Welcome" and printed the position of the pointer at various places. Initially ftell() will return position 0. After append, ftell() will return the last position. If we do fseek() file pointer gets changed and in this case I moved back to 0 position. In append mode, we cannot read data. Why the pointer is in 0 position initially? Also is there any use of fseek in append 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);
// Note that if data is empty, strtok does not work. Use the other method instead.
strtok(buffer,"\n");
}
extern int errno;
int main()
{
FILE *fp1;
char data[50];
fp1=fopen("file1.txt","a");
if(fp1==NULL)
{
// Print the error message
fprintf(stderr,"%s\n",strerror(errno));
}
printf("Initial File pointer position in \"a\" mode = %ld\n",ftell(fp1));
/* Initial file pointer position is 0 even in append mode
As soon as data is write, FP points to the end.*/
// Write some data at the end of the file only
printf("\nEnter some data to be written to the file\n");
readString(data,MAX_BUF_SIZE);
// The data will be appended
fputs(data,fp1);
// File pointer points to the end after write operation
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);
}