代码之家  ›  专栏  ›  技术社区  ›  chmike

在C/C++中实现文件大小的便携方式

  •  8
  • chmike  · 技术社区  · 15 年前

    我需要确定文件的字节大小。

    编码语言是C++,代码应该与Linux、Windows和任何其他操作系统一起工作。这意味着使用标准的C或C++函数/类。

    这种琐碎的需要显然没有琐碎的解决方案。

    6 回复  |  直到 15 年前
        1
  •  7
  •   Dewfy    9 年前

    使用std流,您可以使用:

    std::ifstream ifile(....);
    ifile.seekg(0, std::ios_base::end);//seek to end
    //now get current position as length of file
    ifile.tellg();
    

    如果处理只写文件(std::ofstream),那么方法是另一种方法:

    ofile.seekp(0, std::ios_base::end);
    ofile.tellp();
    
        2
  •  6
  •   Adil    15 年前

    您可以使用stat系统调用:

    #ifdef WIN32 
    _stat64()
    #else
    stat64()
    
        3
  •  3
  •   Sebastian    15 年前

    如果你只需要文件大小,这当然是多余的,但一般来说,我会同意 Boost.Filesystem 用于独立于平台的文件操作。 它包含的其他属性函数中

    template <class Path> uintmax_t file_size(const Path& p);
    

    你可以找到参考资料 here . 虽然Boost库可能看起来很庞大,但我发现它常常能够非常有效地实现一些东西。您也只能提取所需的函数,但这可能很困难,因为Boost相当复杂。

        4
  •  0
  •   graham.reeds    15 年前

    简单的:

    std::ifstream ifs; 
    ifs.open("mybigfile.txt", std::ios::bin); 
    ifs.seekg(0, std::ios::end); 
    std::fpos pos = ifs.tellg();
    
        5
  •  -1
  •   the100rabh    15 年前

    通常我们希望以最可移植的方式完成工作,但在某些情况下,特别是像这样,我强烈建议使用SystemAPI以获得最佳性能。

        6
  •  -1
  •   iplayfast    15 年前

    可移植性要求您使用最小公分母,这将是C.(而不是C++)。 我使用的方法如下。

    #include <stdio.h>
    
    long filesize(const char *filename)
    {
    FILE *f = fopen(filename,"rb");  /* open the file in read only */
    
    long size = 0;
      if (fseek(f,0,SEEK_END)==0) /* seek was successful */
          size = ftell(f);
      fclose(f);
      return size;
    }