首页 > 解决方案 > 使用字符串变量作为文件路径从子目录获取文件 - 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++filecsvifstream

解决方案


如果您可以使用 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以获取目录中的文件。


推荐阅读