暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

C++ 获取文件大小

程序员开发入门 2019-11-07
1441

通常我们在获取文件大小的时候都是用使用C语言的fseek和ftell组合来获取,fsekk将fd设置到文件尾SEEK_END,然后使用ftell的返回值获取大小。

这种做法很常见,但如果遇到大文件就会有问题,比如超过2G的文件。因为ftell返回的是long,在不同的系统环境下长度能支持的最大字节数不同。

其实ANSI C里面还是提供了另外一个接口获取文件属性

fstate

通过man 2 fstate 命令我们可以看到

  1. NAME

  2. stat, fstat, lstat - get file status


  3. SYNOPSIS

  4. #include <sys/types.h>

  5. #include <sys/stat.h>

  6. #include <unistd.h>


  7. int stat(const char *path, struct stat *buf);

  8. int fstat(int fd, struct stat *buf);

  9. int lstat(const char *path, struct stat *buf);


  10. Feature Test Macro Requirements for glibc (see feature_test_macros(7)):


  11. lstat(): _BSD_SOURCE || _XOPEN_SOURCE >= 500

三个函数基本上一样,区别在于fstat使用的入参是fd,lstat是软链文件。

再看下返回struct stat :

  1. struct stat {

  2. dev_t st_dev; /* ID of device containing file */

  3. ino_t st_ino; /* inode number */

  4. mode_t st_mode; /* protection */

  5. nlink_t st_nlink; /* number of hard links */

  6. uid_t st_uid; /* user ID of owner */

  7. gid_t st_gid; /* group ID of owner */

  8. dev_t st_rdev; /* device ID (if special file) */

  9. off_t st_size; /* total size, in bytes */

  10. blksize_t st_blksize; /* blocksize for file system I/O */

  11. blkcnt_t st_blocks; /* number of 512B blocks allocated */

  12. time_t st_atime; /* time of last access */

  13. time_t st_mtime; /* time of last modification */

  14. time_t st_ctime; /* time of last status change */

  15. };

st_size 就是我们需要的文件大小,其它几个属性也很常用。后面的几个时间也经常会用在文件监控。

下面我们写个小程序测试一下:

  1. #include <sys/stat.h>

  2. int getFileSize(const char* dstFileName)

  3. {

  4. struct stat statbuf;

  5. stat(dstFileName,&statbuf);

  6. int size=statbuf.st_size;


  7. return size;

  8. }


  9. int main(int argc ,char* argv[])

  10. {

  11. printf("%d", getFileSize(argv[1])) ;

  12. return 0 ;

  13. }

编译运行:

  1. g++ filesize.cpp

  2. ./a.out /tmp/checkmysql.log

  3. 19533

Done~~


文章转载自程序员开发入门,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论