关于用fseek和ftell获取文件长度的问题,大家讨论一下

antinet 2012-03-12 09:26:25
一个取文件长度的算法一般是这样写
fseek(fp,0,SEEK_END);
ftell(fp);

就是首先把文件指针放到末尾,然后用ftell获取文件指针位置,从而得到文件长度。问题是,函数fseek()的返回值就是文件指针的位置,大家看说明就知道了,那么fseek(fp,0,SEEK_END)本身就会返回文件长度,问什么还要ftell()一下呢?
...全文
907 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
nice_cxf 2012-03-12
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 lishanchao 的回复:]

引用 4 楼 nice_cxf 的回复:

取文件长度不是用stat或fstat么?

不用标准库,移植的时候就要多花一点心思了。
[/Quote]
谁说的stat和fstat不是标准库的?
沭水河畔 2012-03-12
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 nice_cxf 的回复:]

取文件长度不是用stat或fstat么?
[/Quote]
不用标准库,移植的时候就要多花一点心思了。
nice_cxf 2012-03-12
  • 打赏
  • 举报
回复
取文件长度不是用stat或fstat么?
沭水河畔 2012-03-12
  • 打赏
  • 举报
回复
再来一个《The C Programming Language》的附录:
B.1.6 File Positioning Functions

int fseek(FILE *stream, long offset, int origin)
fseek sets the file position for stream; a subsequent read or write will access data beginning at the new position. For a binary file, the position is set to offset characters from origin, which may be SEEK_SET (beginning), SEEK_CUR (current position), or SEEK_END (end of file). For a text stream, offset must be zero, or a value returned by ftell (in which case origin must be SEEK_SET). fseek returns non-zero on error.
long ftell(FILE *stream)
ftell returns the current file position for stream, or -1 on error.
ProgrammingRing 2012-03-12
  • 打赏
  • 举报
回复
MSDN:
If successful, fseek returns 0. Otherwise, it returns a nonzero value. On devices incapable of seeking, the return value is undefined.
沭水河畔 2012-03-12
  • 打赏
  • 举报
回复
Fedora Core 12下不是这样子哦
The rewind() function returns no value. Upon successful completion, fgetpos(), fseek(), fsetpos() return 0,
and ftell() returns the current offset. Otherwise, -1 is returned and errno is set to indicate the error.
nice_cxf 2012-03-12
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 lishanchao 的回复:]

引用 6 楼 nice_cxf 的回复:

引用 5 楼 lishanchao 的回复:

引用 4 楼 nice_cxf 的回复:

取文件长度不是用stat或fstat么?

不用标准库,移植的时候就要多花一点心思了。

谁说的stat和fstat不是标准库的?

我说的:
C/C++ code

NAME
stat, fstat, lstat - ……
[/Quote]
==============
原来你说的是这个意思,那么能告诉我哪个编译器不支持stat 和fstat?至少gcc和vs都支持
沭水河畔 2012-03-12
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 nice_cxf 的回复:]

引用 5 楼 lishanchao 的回复:

引用 4 楼 nice_cxf 的回复:

取文件长度不是用stat或fstat么?

不用标准库,移植的时候就要多花一点心思了。

谁说的stat和fstat不是标准库的?
[/Quote]
我说的:

NAME
stat, fstat, lstat - get file status

SYNOPSIS
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

70,038

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧