当文件以“a”(追加)模式打开时,我正在查看 SO post fseek does not work,当我们以“a”模式打开文件时,我对 ftell() 返回的文件指针的初始值有疑问。我使用包含数据“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);
}