我正在尝试使用相对路径读取c ++中的文件。我知道过去这一直是个问题,但我希望新的std :: filesystem库能帮上忙。仍然无法正常工作。
我有一个简单的test.csv文件。
1 2
3 4
5 6
和我的test.cpp看起来如下:
#include <iostream>
#include <filesystem>
#include <cstdlib>
#include <fstream>
int main(void)
{
std::filesystem::path p{"./test.csv"};
std::filesystem::path p2{"../test.csv"};
// file in same path
auto file = std::ifstream{p};
auto line = std::string();
// read file line by line
auto a = 0, b = 0;
while (file >> a >> b) {
std::cout<< a << ' ' << b << std::endl;
}
file.close();
// try the same for the file in the parent_dir
file.open(p2);
// read file line by line
a = 0, b = 0;
while (file >> a >> b){
std::cout<< a << ' ' << b << std::endl;
}
file.close();
}
第一个路径p可以很好地加载文件并打印输出。第二个(相对于父目录的相对路径不会抱怨,但在运行时不会执行任何操作。从相对路径读取文件的正确方法是什么?