Relative path with fstream c++

最后都变了- 提交于 2019-12-10 15:16:24

问题


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



来源:https://stackoverflow.com/questions/28180103/relative-path-with-fstream-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!