如何在不打开的情况下获得最大文件的大小?

How can I get a size of biggest file without open?

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

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。

还有其他方法吗?

我的 OS 是 Win32。

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

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

虽然有一个符合 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;
}