unsigned long get_file_size(const char *filename)
{
unsigned long size;
FILE* fp = fopen( filename, "rb" );
if(fp==NULL)
{
printf("ERROR: Open file %s failed.\n", filename);
return 0;
}
fseek( fp, SEEK_SET, SEEK_END );
size=ftell(fp);
fclose(fp);
return size;
}
没有想到的是,在程序执行后发现有的文件能正确的获取大小,而有的文件则不能正确的获取到文件大小,检查了代码,也没有发现有什么不对的地方。但是在这过程中发现了一个问题,就是能正确获取大小的文件都是相对比较小的文件,而出现错误的都是很大的文件。于是想到会不会是因为标准 C文件操作函数对超过一定大小的文件不支持所造成的呢,于是Google了一下,没想到猜测是正确的,标准C的文件操作函数不支持对超过2G的文件读取。
问题找到了,看来只有换一种方法来实现了,因为平时很少用到标准C的一些函数,所以,又只有求助于Google了,在看了网上不少的参考文章之后,发现调用stat函数可以正确的得到超大文件的状态信息(当然包括文件大小),于是最终实现了如下的代码:
unsigned long get_file_size(const char *filename)
{
struct stat buf;
if(stat(filename, &buf)<0)
{
return 0;
}
return (unsigned long)buf.st_size;
}
其实,本质是通过接口获取系统中保存的文件信息结点:
All of these system calls return a stat structure, which contains the following fields:
man 2 stat:
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for file system I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */
};