如何在 C 中获取文件的大小?

新手上路,请多包涵

让我们为 这个 问题创建一个补充问题。在 C++ 中获取文件大小的最常用方法是什么?在回答之前,请确保它是可移植的(可以在 Unix、Mac 和 Windows 上执行)、可靠、易于理解并且没有库依赖项(没有 boost 或 qt,但例如 glib 是可以的,因为它是可移植的库)。

原文由 Sophie Sperner 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 714
2 个回答

下面的代码片段完全解决了这篇文章中的问题:)

 ///
/// Get me my file size in bytes (long long to support any file size supported by your OS.
///
long long Logger::getFileSize()
{
    std::streampos fsize = 0;

    std::ifstream myfile ("myfile.txt", ios::in);  // File is of type const char*

    fsize = myfile.tellg();         // The file pointer is currently at the beginning
    myfile.seekg(0, ios::end);      // Place the file pointer at the end of file

    fsize = myfile.tellg() - fsize;
    myfile.close();

    static_assert(sizeof(fsize) >= sizeof(long long), "Oops.");

    cout << "size is: " << fsize << " bytes.\n";
    return fsize;
}

原文由 Sammy 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题