阅读量:5
在C++中,遍历文件有多种方法。以下是几种常见的方法:
- 使用C++标准库中的
库(C++17起可用):
#include
#include
namespace fs = std::filesystem;
int main() {
// 遍历指定目录下的所有文件和子目录
for (const auto& entry : fs::recursive_directory_iterator("path/to/directory")) {
std::cout << entry.path() << std::endl;
}
return 0;
}
- 使用C++标准库中的
头文件(仅适用于类Unix系统):
#include
#include
int main() {
DIR *dir;
struct dirent *entry;
// 打开目录
dir = opendir("path/to/directory");
if (dir == nullptr) {
std::cerr << "Error opening directory" << std::endl;
return 1;
}
// 遍历目录下的所有文件和子目录
while ((entry = readdir(dir)) != nullptr) {
std::cout << entry->d_name << std::endl;
}
// 关闭目录
closedir(dir);
return 0;
}
- 使用第三方库,如nlohmann/json库来处理JSON文件:
#include
#include
#include
using json = nlohmann::json;
int main() {
// 读取JSON文件并解析
std::ifstream file("path/to/file.json");
json j;
file >> j;
// 遍历JSON对象的所有键值对
for (const auto& [key, value] : j.items()) {
std::cout << key << ": " << value << std::endl;
}
return 0;
}
这些方法可以根据具体需求选择使用,其中库是最现代和最推荐的方法,因为它提供了跨平台的解决方案,并且易于使用。
以上就是关于“c++遍历文件有哪些常见方法”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm