fseek(), ftell() 获取文件大小

C手册上说, 使用fseek()时,

* Library implementations are allowed to not meaningfully support SEEK_END (therefore, code using it has no real standard portability).

就是说fseek到SEEK_END有可能是不支持的.

后来发现在 https://groups.google.com/forum/#!topic/comp.lang.c/2G2YL4jkVbM

有个回答:

    A binary stream need not meaningfully support fseek calls with a 
    whence value of SEEK_END. 
 

Some systems might store binary files as a whole number of fixed-length 
blocks, with no information about how many bytes are in the final block. 
On such a system, fseek with SEEK_END might go to the end of the last 
block, even if not that many bytes have been written.  On a UNIX-like 
system, a binary file is stored as an arbitrary sequence of bytes, and 
fseek with SEEK_END works perfectly well.  Code that relies on this will 
not be portable to non-UNIX systems. 

解释了原因, 这样明白以后就稍微放心了.

类似的讨论还有

https://wiki.sei.cmu.edu/confluence/display/c/FIO19-C.+Do+not+use+fseek%28%29+and+ftell%28%29+to+compute+the+size+of+a+regular+file

https://stackoverflow.com/questions/27549718/behaviour-of-fseek-and-seek-end

除此之外, fseek()还有个要注意的地方:

The end-of-file internal indicator of the stream is cleared after a successful call to this function, and all effects from previous calls to ungetc on this stream are dropped.

相关的讨论在 https://bytes.com/topic/c/answers/621808-fseek-clears-eof

猜你喜欢

转载自blog.csdn.net/qq_34352738/article/details/82112379