卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64336本站已运行4115

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

问题:如何在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;
}
卓越飞翔博客
上一篇: python怎么写绝对值
下一篇: python怎么调用库
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏