Home > Backend Development > C++ > How to get file size using C++?

How to get file size using C++?

WBOY
Release: 2024-06-01 14:22:56
Original
586 people have browsed it

Question: How to get file size in C++? Answer: 1. Use the std::ifstream::tellg() member function to get the number of bytes read or written since opening the file stream; 2. Use std::filesystem::directory_iterator to traverse the files in the directory and Use std::ifstream::tellg() to calculate the number of bytes in each file and add them up to get the total size.

How to get file size using C++?

#How to get file size in C++?

In C++, you can use the std::ifstream class to open and read files. This class contains std::ifstream::tellg() member function which returns the number of bytes read or written since the file stream was opened. This can be used to get the size of the file.

Code example:

#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;
}
Copy after login

Practical case:

The following is a method to obtain the total size of all files in a specific directory Example:

#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;
}
Copy after login

The above is the detailed content of How to get file size using C++?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template