你如何确定C中文件的大小? [英] How do you determine the size of a file in C?
问题描述
如何确定文件的大小(以字节为单位)?
How can I figure out the size of a file, in bytes?
#include <stdio.h>
unsigned int fsize(char* file){
//what goes here?
}
推荐答案
在类 Unix 系统上,您可以使用 POSIX 系统调用:stat
路径,或 fstat
已经打开的文件描述符(POSIX 手册页,Linux 手册页).
(从 stdio 流上的 open(2)
或 fileno(FILE*)
获取文件描述符).
On Unix-like systems, you can use POSIX system calls: stat
on a path, or fstat
on an already-open file descriptor (POSIX man page, Linux man page).
(Get a file descriptor from open(2)
, or fileno(FILE*)
on a stdio stream).
基于 NilObject 的代码:
Based on NilObject's code:
#include <sys/stat.h>
#include <sys/types.h>
off_t fsize(const char *filename) {
struct stat st;
if (stat(filename, &st) == 0)
return st.st_size;
return -1;
}
变化:
- 将文件名参数设为
const char
. - 更正了
struct stat
定义,该定义缺少变量名称. - 出错时返回
-1
而不是0
,这对于空文件来说是不明确的.off_t
是有符号类型,所以这是可能的.
- Made the filename argument a
const char
. - Corrected the
struct stat
definition, which was missing the variable name. - Returns
-1
on error instead of0
, which would be ambiguous for an empty file.off_t
is a signed type so this is possible.
如果你想让 fsize()
在出错时打印一条消息,你可以使用这个:
If you want fsize()
to print a message on error, you can use this:
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
off_t fsize(const char *filename) {
struct stat st;
if (stat(filename, &st) == 0)
return st.st_size;
fprintf(stderr, "Cannot determine size of %s: %s
",
filename, strerror(errno));
return -1;
}
在 32 位系统上,您应该使用选项 -D_FILE_OFFSET_BITS=64
编译它,否则 off_t
最多只能保存 2 GB 的值.请参阅使用 LFS"Linux 中的大文件支持 部分了解详情.
On 32-bit systems you should compile this with the option -D_FILE_OFFSET_BITS=64
, otherwise off_t
will only hold values up to 2 GB. See the "Using LFS" section of Large File Support in Linux for details.
这篇关于你如何确定C中文件的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!