如何计算文件的大小(以字节为单位)?
#include <stdio.h>
unsigned int fsize(char* file){
//what goes here?
}
如何计算文件的大小(以字节为单位)?
#include <stdio.h>
unsigned int fsize(char* file){
//what goes here?
}
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的代码:
#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
将只能保存最大为2GB的值.详见Large File Support in Linux页的"使用LFS"一节.