【问题标题】:Get file size with std::ios::ate?使用 std::ios::ate 获取文件大小?
【发布时间】:2012-10-09 01:49:06
【问题描述】:

关于如何测量文件大小的几个主题(参见Using C++ filestreams (fstream), how can you determine the size of a file?C++: Getting incorrect file size)计算文件开头和结尾之间的差异,如下所示:

std::streampos fileSize( const char* filePath ){

    std::streampos fsize = 0;
    std::ifstream file( filePath, std::ios::binary );

    fsize = file.tellg();
    file.seekg( 0, std::ios::end );
    fsize = file.tellg() - fsize;
    file.close();

    return fsize;
}

但是我们可以在最后打开它并采取措施,而不是一开始就打开文件,就像这样:

std::streampos fileSize( const char* filePath ){

    std::ifstream file( filePath, std::ios::ate | std::ios::binary );
    std::streampos fsize = file.tellg();
    file.close();

    return fsize;
}

它会起作用吗?如果不是,为什么?

【问题讨论】:

  • 只是一个旁注,对close 的调用是不必要的。
  • 可能会起作用,但不确定这是获取文件大小的最佳方法。
  • 如果我需要获取文件大小,我通常会这样调用:std::ifstream file( filepath, std::ios::ate | std::ios::binary);int fileLength = 0;file.seekg(0, std::ios::end);fileLength = file.tellg();file.seekg(0, std::ios::beg);if(fileLength == -1) { //error stuff here}等等。我相信流位置的差异,它是一个内部字符数组,所以位置 1,可以偏移 0。虽然,这部分我并不积极
  • @SethCarnegie:为什么不需要关闭电话?
  • 因为ifstream是一个RAII对象,当它被销毁时会关闭它的文件。

标签: c++ file size fstream standard-library


【解决方案1】:

它应该可以正常工作。 C++ 标准中提到了std::ios::ate

ate - 打开并在打开后立即结束

当手动打开然后搜索成功时,它没有理由失败。而tellg 在任何一种情况下都是一样的。

【讨论】:

    猜你喜欢
    • 2015-10-26
    • 2023-03-31
    • 2012-08-28
    • 2020-11-03
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多