gpt4 book ai didi

c++ - 使用 std::ios::ate 获取文件大小?

转载 作者:太空宇宙 更新时间:2023-11-04 12:04:27 25 4
gpt4 key购买 nike

关于如何测量文件大小的几个主题(参见 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;
}

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

最佳答案

它应该工作得很好。 C++ 标准说明了 std::ios::ate

ate - open and seek to end immediately after opening

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

关于c++ - 使用 std::ios::ate 获取文件大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12791807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com