我的项目主目录中有一个子目录,称为“数据”。在此目录中,有一些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;
}
据我了解,您只想相应地构建文件路径。 例如,看起来可能像这样:
正如AskoldIlvento已经建议的那样,您应该(如果可能)使用std :: filesystem等,以获得更好的兼容性。或使用诸如boost(boost :: fileystem)之类的库。
The
ifstream
constructor accepts either achar *
or aconst std::string &
argument, so you have no reason to use._str()
. You could simply change your line with: