C语言 你如何通过 fd 获取文件大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6537436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you get file size by fd?
提问by R__
I know I can get file size of FILE *by fseek, but what I have is just a INT fd.
我知道我可以获得FILE *by 的文件大小fseek,但我所拥有的只是一个 INT fd。
How can I get file size in this case?
在这种情况下如何获取文件大小?
回答by Hasturkun
回答by Seth Robertson
fstat will work. But I'm not exactly sure how you plan the get the file size via fseek unless you also use ftell (eg. fseek to the end, then ftell where you are). fstat is better, even for FILE, since you can get the file descriptor from the FILE handle (via fileno).
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 */
…
};
回答by Michael Potter
I like to write my code samples as functions so they are ready to cut and paste into the code:
我喜欢将代码示例编写为函数,以便它们可以剪切并粘贴到代码中:
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);
}
NOTE: @AnttiHaapala pointed out that st_size is not an int so this code will fail/have compile errors on 64 machines. To fix change the return value to a 64 bit signed integer or the same type as st_size (off_t).
注意:@AnttiHaapala 指出 st_size 不是 int 所以此代码将在 64 台机器上失败/编译错误。修复将返回值更改为 64 位有符号整数或与 st_size (off_t) 相同的类型。

