让我们为 这个 问题创建一个补充问题。在 C++ 中获取文件大小的最常用方法是什么?在回答之前,请确保它是可移植的(可以在 Unix、Mac 和 Windows 上执行)、可靠、易于理解并且没有库依赖项(没有 boost 或 qt,但例如 glib 是可以的,因为它是可移植的库)。
原文由 Sophie Sperner 发布,翻译遵循 CC BY-SA 4.0 许可协议
让我们为 这个 问题创建一个补充问题。在 C++ 中获取文件大小的最常用方法是什么?在回答之前,请确保它是可移植的(可以在 Unix、Mac 和 Windows 上执行)、可靠、易于理解并且没有库依赖项(没有 boost 或 qt,但例如 glib 是可以的,因为它是可移植的库)。
原文由 Sophie Sperner 发布,翻译遵循 CC BY-SA 4.0 许可协议
下面的代码片段完全解决了这篇文章中的问题:)
///
/// 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 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答1.6k 阅读✓ 已解决
有关 C++ 文件的更多信息,请参阅 http://www.cplusplus.com/doc/tutorial/files/ 。
编辑:这个答案不正确,因为 tellg() 不一定返回正确的值。见 http://stackoverflow.com/a/22986486/1835769