问题:如何在c++++中获取文件大小?答案:1. 使用std::ifstream::tellg()成员函数获取自打开文件流以来的读取或写入的字节数;2. 使用std::filesystem::directory_iterator遍历目录中的文件,并使用std::ifstream::tellg()计算每个文件的字节数,并累加得到总大小。
如何在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++获取文件大小?的详细内容,更多请关注知识资源分享宝库其它相关文章!
版权声明
本站内容来源于互联网搬运,
仅限用于小范围内传播学习,请在下载后24小时内删除,
如果有侵权内容、不妥之处,请第一时间联系我们删除。敬请谅解!
E-mail:dpw1001@163.com
发表评论