0

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?

Mike
  • 3,775
  • 8
  • 39
  • 79
  • Relative paths are relative to the process' current working directory. Are you sure that the cwd is actually what you think it is? For example, if you happen to use Visual Studio, the default working directory during debugging of C++ projects is the project directory (the directory where the .vcproj file is located) and **not** the directory of the exe file. – Timo Apr 09 '20 at 18:08
  • What compiler, and OS are you using? – cigien Apr 09 '20 at 18:56
  • Linux, gcc in visual studio code. @Timo cleared up the issue on the process cwd. My main problem is that I want a stable location for my test data files that compiles both on linux and windows. – Mike Apr 09 '20 at 19:20
  • Actually, I solved my issue with the suggestions in: https://stackoverflow.com/questions/59690736/how-to-get-a-relative-path-for-cmake-unit-tests – Mike Apr 09 '20 at 21:13

0 Answers0