从使用追加模式打开的文件中读取 [英] Reading from a file opened using append mode

查看:65
本文介绍了从使用追加模式打开的文件中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个非常愚蠢的问题,但是我正在修改其他人的代码,看来我需要从以追加模式打开的文件中读取内容.我试图到文件的开头,但是没有读取任何内容.我知道我可以将模式更改为rw,但是我想知道为什么 fseek 无法正常工作.在手册页中确实写了write忽略了 fseek ,但是与读无关.

It might be a very dumb question but I am modifying someone else's code and it seems I need to read from a file that was opened in append mode. I tried to fseek to the beginning of the file but nothing is being read. I know I can change the mode to rw but I wanted to know why fseek is not working. In the man page it does say write ignores fseek but nothing about read though.

推荐答案

只有一个指针,该指针最初位于文件的开头,但是当尝试执行写操作时,它将移动到文件的末尾.您可以使用fseek对其进行重新定位,也可以在文件中的任何位置后退以进行读取,但是写入操作会将其移回到文件末尾.

There is just one pointer which initially is at the start of the file but when a write operation is attempted it is moved to the end of the file. You can reposition it using fseek or rewind anywhere in the file for reading, but writing operations will move it back to the end of file.

在追加模式下打开时,文件指针将在每次写入之前返回到文件末尾.您可以使用fseek重新定位指针以进行读取,但是一旦调用写入文件的函数,指针就会回到文件末尾.

When you open in append mode, the file pointer is returned to the end of file before every write. You can reposition the pointer with fseek for reading, but as soon as you call a function that writes to the file, the pointer goes back to the end of file.

引用了C标准的相应部分.

The answer at Does fseek() move the file pointer to the beginning of the file if it was opened in "a+b" mode? references the appropriate section of the C standard.

如果要写入文件中的任意位置,请使用"w +"模式.现有文件将被覆盖.

Use the "w+" mode if you would like to write to arbitrary places in file. An existing file will be overwritten.

如果您想先附加到现有文件,然后再查找到任意位置,请使用"r +"后跟

If you would like to append to an existing file initially, but then fseek to arbitrary place, use "r+" followed by

fseek(f, 0, SEEK_END)

希望有帮助.

这篇关于从使用追加模式打开的文件中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆