I am trying to read a file in c++ using a relative path. I know this has been a problem in the past, but was hoping the new std::filesystem library would help out. Still I can't get it to work.
I have a simple test.csv file.
1 2
3 4
5 6
and my test.cpp looks as follows:
#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();
}
the first path p loads the file fine and prints output. The second (relative path to the parent directory does not complain, but does not do anything at runtime. What is the correct way to read files from relative paths?