(有效值也可以为0x1a啊,这难道不是bug吗,exm?)
网友给出的依据是MSDN中关于fopen函数的一段话:
Open in text (translated) mode. In this mode, CTRL+Z is interpreted as an EOF character on input. In files that are opened
for reading/writing by using "a+", fopen checks for a CTRL+Z at the end of the file and removes it, if possible. This is done because
using fseek and ftell to move within a file that ends with CTRL+Z may cause fseek to behave incorrectly near the end of the file.
我也打开帮助文档,看到了这句话,官方翻译是:
在文本(转换)模式下打开。 在此模式下,CTRL+Z 将在输入时解释为 EOF 字符。 在使用 "a+" 打开以进行读取/写入
的文件中,fopen 将检查文件末尾的 CTRL+Z 并将其删除(如果可能)。 这是因为使用 fseek 和 ftell 在以 CTRL+Z 结尾的
文件中移动时,可能导致 fseek 在文件末尾附近错误运行。
于是我写了以下一小段代码进行测试
Do you see the problem yet? The function tests the end-of-file indicator, not the stream itself. This means that another
function is actually responsible for setting the indicator to denote EOF has been reached. This would normally be done by the
function that performed the read that hit EOF. We can then follow the problem to that function, and we find that most read
functions will set EOF once they've read all the data, and then performed a final read resulting in no data, only EOF.
With this in mind, how does it manifest itself into a bug in our snippet of code? Simple... as the program goes through the loop
to get the last line of data, fgets() works normally, without setting EOF, and we print out the data. The loop returns to the
top, and the call to feof() returns FALSE, and we start to go through the loop again. This time, the fgets() sees and sets EOF,
but thanks to our poor logic, we go on to process the buffer anyway, without realising that its content is now undefined (most
likely untouched from the last loop).
他的意思就是说呢feof并非检测当前文件内容是否是文件结束标识符,
而是检测一个标志,这个标志由其他函数设置,他这里提到了fgets函
数在获取内容为空后,会设置这个标志为TRUE,意思就是说就算指
针指向文件结尾,没有函数设置这个标志,feof就不会认为已经到了
文件结尾。那么我们就用下面代码做个小测试: