首頁  >  文章  >  後端開發  >  如何使用C++取得檔案大小?

如何使用C++取得檔案大小?

WBOY
WBOY原創
2024-06-01 14:22:56455瀏覽

問題:如何在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