【问题标题】:How to get the size of a file [duplicate]如何获取文件的大小[重复]
【发布时间】:2012-10-09 07:00:45
【问题描述】:

可能重复:
Using C++ filestreams (fstream), how can you determine the size of a file?
file size in c program

我想检索文件的大小,为此我以这种方式实现

(void)fseek(m_fp, 0, SEEK_END); // Set the file pointer to the end of the file
pFileSize = ftell(m_fp);        // Get the file size
(void)fseek(m_fp, oldFilePos, SEEK_SET);  // Put back the file pointer at the original location

这是不可行的,有没有其他方法可以获取文件大小或检查文件是否包含数据

【问题讨论】:

  • 您使用的是哪个操作系统?
  • 为什么这样做不可行?
  • @moooeeeep 因为它调用未定义的行为?来自 C 标准:A binary stream need not meaningfully support fseek calls with a whence value of SEEK_END.Setting the file position indicator to end-of-file, as with fseek(file, 0, SEEK_END), has undefined behavior for a binary stream...
  • 如果你不怕前沿,std::tr2::file_size

标签: c++ c file-io


【解决方案1】:

你可以使用统计

#include <sys/types.h>
#include <sys/stat.h>
#if defined (_WIN32)
#  include <io.h> // make portable for windows
#else
#include <unistd.h>
#endif

struct stat st;
stat (filename, &st);
std::cout << st.st_size;

【讨论】:

  • 请注意,stat 不是 C 或 C++ 的一部分,而是 POSIX。
  • fstat() 或 fstat64() 是使用 FILE * 的 stat() 的变体。鉴于您的代码中已经有 m_fp,我建议您使用 fstat()。
  • fstat () 使用 int 文件句柄(由 open 返回)而不是 FILE*(来自 fopen
【解决方案2】:

如果是二进制流,那么pFileSize就是从oldFilePos到文件末尾的字节数。

【讨论】:

  • 来自 C 标准:A binary stream need not meaningfully support fseek calls with a whence value of SEEK_END., Setting the file position indicator to end-of-file, as with fseek(file, 0, SEEK_END), has undefined behavior for a binary stream...
【解决方案3】:

您所写的是一种 100% 多平台的方式来满足您的需求。使用操作系统的调用来做更多事情,stat() 在类 Unix 操作系统上或GetFileAttributesEx() 在 Windows 上。

【讨论】:

  • -1。不,这不对。来自 C 标准:A binary stream need not meaningfully support fseek calls with a whence value of SEEK_END.Setting the file position indicator to end-of-file, as with fseek(file, 0, SEEK_END), has undefined behavior for a binary stream...
  • 真的有这样的平台不支持stdio中的SEEK_END吗?
  • 我不能肯定地告诉你哪些平台(编译器/stdlibs/OSes)不支持它,但我想我被它打败过一次。
猜你喜欢
  • 2018-07-05
  • 2021-02-04
  • 2018-05-08
  • 1970-01-01
  • 1970-01-01
  • 2014-11-27
  • 1970-01-01
相关资源
最近更新 更多