首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用std::ios::ate获取文件大小?

使用std::ios::ate获取文件大小?
EN

Stack Overflow用户
提问于 2012-10-09 09:49:07
回答 1查看 5.1K关注 0票数 1

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

代码语言:javascript
复制
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;
}

但是,我们可以在最后打开文件,而不是在开始时打开文件,然后采取如下措施:

代码语言:javascript
复制
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;
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-09 10:04:35

它应该工作得很好。关于std::ios::ate,C++标准规定了

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

当手动打开然后查找会成功时,它没有理由会失败。无论哪种情况,tellg都是一样的。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12791807

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档