我尝试了以下代码,并使用包含数据“Hello Welcome”的file1.txt在各个位置上打印了指针的位置。最初,ftell()将返回位置0。追加后,ftell()将返回最后一个位置。如果我们执行fseek(),文件指针将更改,在这种情况下,我回到了0位置。
在追加模式下,我们无法读取数据。为什么指针最初处于0位置?此外,追加模式下是否有fseek的任何用途?
#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);
}