5

I try to load a file with fstream. The code looks like this

file.open("../levels/level0.lvl");
if (file.is_open()) {
    while (!file.eof()) {
        std::getline(file, Str);
        list = ReadLine(Str, list);
    }
}

But it loads nothing. Yes only if the path is absolute. How can I make the path relative?

The folder "levels" is hosted in the debug folder. same folder as the exe.

SaschaDeWaal
  • 149
  • 2
  • 15
  • 2
    Your relative path is valid. Are you possibly confusing your *active directory* with *your executable's directory*? – Drew Dormann Jan 27 '15 at 21:14
  • You're right. Thanks and sorry for this stupid mistake – SaschaDeWaal Jan 27 '15 at 21:23
  • 3
    @Beatnory _`while (!file.eof())`_ You should also note: [**Why is iostream::eof inside a loop condition considered wrong?**](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – πάντα ῥεῖ Jan 27 '15 at 21:50

2 Answers2

8

"The folder "levels" is hosted in the debug folder. same folder as the exe."

It doesn't matter in which position the levels folder is in relation to the executable's path.
The relevant folder to determine the relative path is the working directory where your executable is actually started from.


See here: fstream doesn't resolve path also.

Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • Aren't these the same though? Where the executable is starting from and where the folder is? – Zap Oct 14 '19 at 14:58
0

Path handling is OS specific. The correct way to handle this is to add a way of the user specifying the path to your application and then use that path. For example, you could add a command line option --level-file=<path>. Then your program can read the path from that option and pass it to the fstream constructor.

See my answer to this question for more: https://stackoverflow.com/a/40980510/2345997

Community
  • 1
  • 1
user1976
  • 353
  • 4
  • 15