>  기사  >  백엔드 개발  >  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으로 문의하세요.