如何计算文件大小(以字节为单位)?
#include <stdio.h>
unsigned int fsize(char* file){
//what goes here?
}
最佳答案
基于NilObject的代码:
#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
是带符号的类型,因此这是可能的。 如果您希望
fsize()
在错误时显示一条消息,则可以使用以下命令:#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\n",
filename, strerror(errno));
return -1;
}
在32位系统上,应使用
-D_FILE_OFFSET_BITS=64
选项进行编译,否则off_t
将仅保留2 GB以下的值。有关详细信息,请参见Large File Support in Linux的“使用LFS”部分。关于c - 您如何确定C中文件的大小?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8236/