Set*_*son 18
fstat会起作用.但我不确定你如何计划通过fseek获取文件大小,除非你也使用ftell(例如fseek到最后,然后ftell你在哪里).fstat更好,即使对于FILE,因为你可以从FILE句柄获取文件描述符(通过fileno).
stat, fstat, lstat - get file status
int fstat(int fd, struct stat *buf);
struct stat {
…
off_t st_size; /* total size, in bytes */
…
};
Run Code Online (Sandbox Code Playgroud)
Has*_*kun 17
您可以使用lseek
with SEEK_END
作为原点,因为它返回文件中的新偏移量,例如.
off_t fsize;
fsize = lseek(fd, 0, SEEK_END);
Run Code Online (Sandbox Code Playgroud)
我喜欢将代码示例编写为函数,以便可以将它们剪切并粘贴到代码中:
int fileSize(int fd) {
struct stat s;
if (fstat(fd, &s) == -1) {
int saveErrno = errno;
fprintf(stderr, "fstat(%d) returned errno=%d.", fd, saveErrno);
return(-1);
}
return(s.st_size);
}
Run Code Online (Sandbox Code Playgroud)
注意:@AnttiHaapala 指出 st_size 不是 int,因此此代码在 64 台机器上将失败/有编译错误。要修复此问题,请将返回值更改为 64 位有符号整数或与 st_size (off_t) 相同的类型。
归档时间: |
|
查看次数: |
20807 次 |
最近记录: |