gpt4 book ai didi

c - ftell() 在附加模式下返回的文件指针位置的初始值

转载 作者:太空狗 更新时间:2023-10-29 15:34:32 28 4
gpt4 key购买 nike

我正在查看 SO 帖子 fseek does not work when file is opened in "a" (append) mode当我们以“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);
}

最佳答案

你问

Why the pointer is in 0 position initially?

在您提出的一般性级别上唯一可用的答案,因为它是您的特定实现做出的选择。标准说:

If a file can support positioning requests (such as a disk file, as opposed to a terminal), then a file position indicator associated with the stream is positioned at the start (character number zero) of the file, unless the file is opened with append mode in which case it is implementation-defined whether the file position indicator is initially positioned at the beginning or the end of the file.

( C2011, 7.21.3/1 )

因此,对于以追加模式打开的文件,实现可以选择将位置初始设置为文件的开头或末尾。前者与以任何其他模式打开文件时的行为一致,并反射(reflect)下一次读取将发生的位置(对于允许读取的追加模式,例如“a+”);后者反射(reflect)了第一次写入的位置。我个人更喜欢前者,因为您不能依赖以追加模式打开的文件的文件位置来反射(reflect)下一次写入的位置(该位置始终可以通过 fseek() 更改) .

Also is there any use of fseek in append mode?

它的主要用途与以仅追加模式打开的文件无关。不过,我不准备说它没有用处,而且我当然不希望它仅仅因为传递给它这样的文件就出错。该问题表明您对文件位置的概念有误。除了第一次打开文件时,它(对于支持它的流)只是该流上最后一次 I/O 操作产生的位置,其中 fseek() 是一个 bona fide I/O 操作。

当然,fseek() 在正常使用打开文件进行读取和追加时非常明智。

关于c - ftell() 在附加模式下返回的文件指针位置的初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46892945/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com