int filesize(FILE * handle)
{
int filesize;
int old_pointer = ftell(handle);
fseek(handle, 0, SEEK_END);
filesize = ftell(handle);
fseek(handle, old_pointer, SEEK_SET);
return filesize;
}
这是函数返回文件大小的好方法吗?
答案 0 :(得分:2)
这是一种方法,只要您的文件不是太大(对于32位系统或Windows 64位,意味着不超过2 GiB)。它具有或多或少在任何平台上工作的优点。当然,ftell()
会返回long
,而不是int
(因此,对于64位非Windows系统,只要您修复,它可以报告的文件要大得多)适当的代码)。但是,需要四个函数调用才有点贵。
POSIX替代方案为stat()
,lstat()
和fstat()
。
Windows API中会有类似物。
答案 1 :(得分:1)
我个人使用stat
家族的功能,就像这样。另请注意,int
对于返回值可能太小(特别是在32位系统上); off_t
保证可以正常使用。
off_t filesize(FILE *handle) {
struct stat statbuf;
if (fstat(fileno(handle), &statbuf) != 0) {
// handle an error
} else {
return statbuf.st_size;
}
}
另请注意,使用标准stat()
代替fstat()
可以轻松调整此功能,以便用于尚未打开的文件。
答案 2 :(得分:0)
如果您使用的是* nix,则可以使用stat()
或fstat()
。
答案 3 :(得分:0)
使用stat
:
#include <sys/stat.h>
int stat(const char *path, struct stat *buf);
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 */
};