如何使用C++获取文件大小?

问题:如何在c++++中获取文件大小?答案:1. 使用std::ifstream::tellg()成员函数获取自打开文件流以来的读取或写入的字节数;2. 使用std::filesystem::directory_iterator遍历目录中的文件,并使用std::ifstream::tellg()计算每个文件的字节数,并累加得到总大小。

如何使用C++获取文件大小?

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

在C++中,您可以使用std::ifstream类来打开和读取文件。该类包含std::ifstream::tellg()成员函数,它返回自打开文件流以来读取或写入的字节数。这可以用来获取文件的大小。

代码示例:

立即学习“C++免费学习笔记(深入)”;

#include #include int main() {  // 打开文件  std::ifstream file("myfile.txt");    // 获取文件的大小  file.seekg(0, std::ios::end);  int file_size = file.tellg();    // 打印文件大小  std::cout << "The file size is: " << file_size << " bytes" << std::endl;    file.close();  return 0;}

实战案例:

以下是一个获取特定目录下所有文件的总大小的示例:

#include #include #include int main() {  std::filesystem::path directory_path("my_directory");    // 遍历目录中的文件  int total_file_size = 0;  for (const auto& entry : std::filesystem::directory_iterator(directory_path)) {    if (entry.is_regular_file()) {      // 打开文件      std::ifstream file(entry.path());            // 获取文件大小并累加到总和      file.seekg(0, std::ios::end);      total_file_size += file.tellg();            file.close();    }  }    // 打印总文件大小  std::cout << "The total size of all files in the directory is: " << total_file_size << " bytes" << std::endl;  return 0;}

以上就是如何使用C++获取文件大小?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1453179.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月18日 05:45:06
下一篇 2025年12月18日 05:45:21

相关推荐

发表回复

登录后才能评论
关注微信