首页  >  文章  >  后端开发  >  如何使用C++获取文件大小?

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

WBOY
WBOY原创
2024-06-01 14:22:56456浏览

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

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

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

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

代码示例:

#include <iostream>
#include <fstream>

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 <iostream>
#include <fstream>
#include <filesystem>

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++获取文件大小?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn