c++ - 使用字符串变量作为文件路径从子目录获取文件 - C++
问题描述
我的项目主目录中有一个名为“data”的子目录。在这个目录中,有一些 csv 文件和一个文本文件,文本文件包含我要从中读取数据的一些 csv 文件的名称。使用while循环,我想从文本文件'infile'中获取每个文件名,将其存储到字符串'files'中,并使用此字符串变量打开子目录中的每个文件。我只是不知道如何使用此字符串变量访问子目录。我在下面的代码中所做的是将要使用的文件移动到我的主目录中,它可以按预期工作,但我想通过访问子目录来实现相同的目的。有什么建议么?
string files;
ifstream infile("data\\met_index.txt"); //Open the text file that shows the csv files needed
if(!infile) //Exits the program and outputs this message if the file is not found
{
cout << "File not found.";
return -1;
}
Vector<string> headers; //A vector of type String to hold the headers for each column
while(getline(infile, files))
{
ifstream datafile(files.c_str()); // How do I access sub directory here?
if(!datafile) //Exits the program and outputs this message if the file is not found
{
cout << "File not found.";
return -1;
}
cout << "File: " << files << endl;
}
解决方案
如果您可以使用 C++17 并且您的编译器支持该filesystem
库,那么您应该使用它以获得更好的可移植性。
#include <iostream>
#include <string>
#include <vector>
#include <filesystem>
#include <fstream>
namespace fs = std::filesystem;
int main() {
const fs::path directory_path = "data";
std::ifstream infile{directory_path / "met_index.txt"};
if (!infile){
std::cerr << "met_index.txt not found!\n";
return -1;
}
std::vector<fs::path> file_paths{};
std::string file_input;
while(std::getline(infile, file_input)) {
const fs::path file_path = directory_path / file_input;
if(fs::exists(file_path)) {
file_paths.push_back(file_path);
}
}
for(const fs::path& file_path : file_paths) {
std::cout << file_path << '\n';
}
}
请记住,您需要提供编译器标志才能使用 C++17 进行编译,如果您使用的是 g++ 或 clang++,您可能需要将文件系统与-lstdc++fs
.
此外,如果您met_index.txt
仅使用文件来存储和读取目录中的文件data
以便轻松访问它们,则应查看directory_iterator以获取目录中的文件。
推荐阅读
- sql - 合并多个数据类型完全相同的表,并添加一列来标识源表
- bixby - 如何获取用户信息?
- c# - 执行 caml 查询以获取查找字段:“无法完成此操作。请重试。”?
- python - pandas.DataFrame.copy(deep=True) 实际上并不创建深拷贝
- zabbix - Zabbix 自定义报表开发
- python - 使用 selenium 更快地进行 Webscraping(或更快的替代方案)
- flutter - 如何获取每个选项卡上tabview生成列表的项目索引?
- c# - c#在字符串中增加数字
- sql-server - 查询更改速度(34 秒 vs 0 秒),没有执行计划缓存没有数据/架构更改(从 EF Core 生成的 SQL)
- javascript - D3 在特定级别折叠树(错误的动画)