ホームページ  >  記事  >  バックエンド開発  >  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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。