gpt4 book ai didi

c++ - 在二进制追加中获取 ftell() 的问题

转载 作者:太空狗 更新时间:2023-10-29 20:02:42 25 4
gpt4 key购买 nike

我有一些代码在服务器上运行,直到它被移动到不同的系统。问题似乎出在这里:

给定一个我在别处定义的结构:

user1_type user1;              /* structure containing user data */
user1_type *user1_ptr=&user1;

这个例程将记录追加到文件的末尾

if ((dfile=fopen(filename,"ab+"))==NULL)  
error_message("Unable to open file for append.",filename,1);
else { /* append data */
user1.recid=ftell(dfile); /* update file position */

fwrite(user1_ptr,sizeof(user1),1,dfile);
fflush(dfile);
fclose(dfile);

我可以确认数据已附加到文件中,但 user1.recid 的值始终返回 0 - 知道为什么吗?

更新:看起来问题不是所有实现都需要在 fopen() 之后使用 fseek()。我显然需要一个 fseek(dfile,0,SEEK_END);在我追加时执行 ftell() 之前。但是如果我想从文本或二进制文件的开头读取,是否也习惯于在 fopen 之后放置一个 fseek()?它是否因文件类型而异?

最佳答案

来自 MSDN 的文档 ftell

The position returned by ftell() is expressed as an offset relative to the beginning of the stream

If no I/O operation has yet occurred on a file opened for appending, the file position is the beginning of the file.

这使您相对于开头的偏移量为 0。

因此,当您调用 user1.recid=ftell(dfile); 时,流上还没有发生任何 I/O 操作,因此 ftell() 返回 0,表示该文件指针位置在开头。

关于c++ - 在二进制追加中获取 ftell() 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36896230/

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