【问题标题】:How can I get a size of biggest file without open?如何在不打开的情况下获得最大文件的大小?
【发布时间】:2015-08-20 12:12:50
【问题描述】:

我知道有<sys/stat.h> 标头但是:

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 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 */
};

off_t 的最大值是 2147483647(在我的机器上),小于 2GB。

还有其他方法吗?

我的操作系统是 Win32。

【问题讨论】:

  • 哪个操作系统?您有一个系统 api 来询问文件大小。无需打开。
  • 有些系统提供stat64

标签: c++ windows filesize


【解决方案1】:

虽然有一个符合 POSIX 的 stat64 函数,但它在 Windows 上不可用(正如另一个答案中提到的,有一个 _stat64 函数)。

在 Windows 中最适合使用的函数是GetFileAttributesEx

例如:

BOOL result;
WIN32_FILE_ATTRIBUTE_DATA fad;
LONGLONG filesize;

result = GetFileAttributesEx(filename, GetFileExInfoStandard, &fad);
if (result) {
    filesize = ((LONGLONG)fad.nFileSizeHigh << 32) + fad.nFileSizeLow;
}

【讨论】:

【解决方案2】:

对于 Windows 上的文件操作,您有两种选择。

  • 找到适当的标准或半标准 C 或 POSIX 函数 - 在本例中为 _stat64。如果您尝试编写更可移植的代码,这会更有用,但即便如此,也经常与其他平台不兼容。 (例如,Linux 没有_stat64;相反,它使用#define 使stat 支持64 位。)
  • 使用适当的 Windows API 函数 - 在本例中为 GetFileAttributesEx。对于纯 Windows 应用,这可能比尝试使用标准或半标准 C 和 POSIX 函数更容易并且可能会公开更多功能。

【讨论】:

  • 如果提问者对所有文件信息不感兴趣,GetFileSizeEx 可能就足够了。
  • @WernerHenze 该函数的第一个参数是一个 HANDLE,这意味着事先打开文件。 OP 要求提供一种无需打开即可获取文件大小的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-21
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
  • 2021-09-01
相关资源
最近更新 更多