Relative path with fstream c++

2019-06-21 03:57发布

问题:

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.

回答1:

"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.



回答2:

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