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

本文探讨了C标准中关于fseek函数对SEEK_END的支持情况,解释了不同系统对二进制文件处理方式导致的不兼容性,并提到了EOF标志清除和ungetc的影响。此外,文章强调了fseek在不同平台上的注意事项,包括对非UNIX系统的移植问题.

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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. 

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

类似的讨论还有

FIO19-C. Do not use fseek() and ftell() to compute the size of a regular file - SEI CERT C Coding Standard - Confluence

c - behaviour of fseek and SEEK_END - Stack Overflow

除此之外, 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.

相关的讨论在 fseek() clears EOF? - C / C++

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值