获取文件大小的方法有两种,一种是利用文件头和文件尾的偏移字节数来得到文件大小,另一种是利用文件状态信息中记录的文件总字节数来获取文件大小。利用 fseek()
与 ftell()
函数可以计算出一个文件的大小。fseek()
函数用于设置文件指针 stream 的位置,ftell()
函数用于得到文件位置指针当前位置相对于文件首的偏移字节数。利用 stat()
函数可以获取文件的状态信息,包括文件大小,文件类型等。
#include
int fseek(FILE *stream, long offset, int whence);
long ftell(FILE *stream);
stream
– 指向 FILE 对象的指针offset
– 相对 whence 的偏移量,以字节为单位(正数或负数)whence
– 设定从文件的哪里开始偏移。取值为:SEEK_SET(文件开头)、SEEK_CUR(当前位置)、SEEK_END(文件结尾)。#include
int main(int argc, char const *argv[]) {
long size = 0;
FILE *fp = fopen("/usr/bin/ls", "r");
fseek(fp, 0, SEEK_END);
size = ftell(fp);
printf("size: %ld\n", size);
/* fseek(fp, 0, SEEK_SET); */
fclose(fp);
return 0;
}
/usr/bin/ls
文件fseek()
函数并指向文件结尾stat()
函数获取的是文件的状态信息,不仅仅包含文件大小,还包含文件类型,用户 ID 等信息;该函数返回一个 struct stat
结构体,里面包含以下成员:
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* Inode number */
mode_t st_mode; /* File type and mode */
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; /* Block size for filesystem I/O */
blkcnt_t st_blocks; /* Number of 512B blocks allocated */
/* Since Linux 2.6, the kernel supports nanosecond
precision for the following timestamp fields.
For the details before Linux 2.6, see NOTES. */
struct timespec st_atim; /* Time of last access */
struct timespec st_mtim; /* Time of last modification */
struct timespec st_ctim; /* Time of last status change */
#define st_atime st_atim.tv_sec /* Backward compatibility */
#define st_mtime st_mtim.tv_sec
#define st_ctime st_ctim.tv_sec
};
文件大小信息保存在 st_size
变量中,以字节为单位。
#include
int stat(const char *pathname, struct stat *statbuf);
struct stat
的对象指针errno
中,可以通过 strerror()
函数获取错误码的字符串。#include
#include // included for stat()
int main(int argc, char const *argv[]) {
struct stat statbuf;
stat("/usr/bin/ls", &statbuf);
printf("size: %ld\n", statbuf.st_size);
return 0;
}
statbuf
stat()
函数获取文件状态,结果存储在 statbuf
变量中statbuf.st_size
欢迎关注我的公众号:飞翔的小黄鸭
也许会发现不一样的风景
▽ \bigtriangledown ▽ C/C++读写二进制文件