How to use fstream objects with relative path?

前端 未结 7 1884
终归单人心
终归单人心 2020-12-03 02:53

Do I always have to specify absolute path for objects instantiated from std::fstream class? In other words, is there a way to specify just relative path to them

相关标签:
7条回答
  • 2020-12-03 03:11

    The behaviour is OS specific. Therefore, the best way to handle this IMHO is to make it somebody else's problem. Read the path to the file to open as a string from the user (e.g: command line argument, config file, env variable etc..) then pass that string directly to the constructor of fstream. Document that this is how your program behaves.

    I wrote more about path manipulation here: https://stackoverflow.com/a/40980510/2345997

    0 讨论(0)
  • 2020-12-03 03:11

    Say you have a src folder directly under your project directory and the src folder contains another tmp_folder folder which contains a txt file named readMe.txt. So the txt file can be read in this way

    std::ifstream fin("../src/tmp_folder/readMe.txt");
    
    0 讨论(0)
  • 2020-12-03 03:18

    If you have an .exe file running from C:\Users\Me and you want to write a file to C:\Users\Me\You\text.txt, then all what you need to do is to add the current path operator ., so:

    std::ifstream ifs(".\\you\\myfile.txt");
    

    will work

    0 讨论(0)
  • 2020-12-03 03:19

    On linux also:

    // main.cpp
    int main() {
        ifstream myFile("../Folder/readme.txt");
        // ...
    }
    

    Assuming the folder structure is something like this:

    /usr/Douments/dev/MyProject/main.cpp /usr/Documents/dev/MyProject/Folder/readme.txt

    0 讨论(0)
  • 2020-12-03 03:23

    You can specify a path relative to current directory. On Windows you may call GetCurrentDirectory to retrieve current directory or call SetCurrentDirectory to set current directory. There are also some CRT functions available.

    0 讨论(0)
  • 2020-12-03 03:32

    You can use relative paths. They're treated the same as relative paths for any other file operations, like fopen; there's nothing special about fstream in that regard.

    Exactly how they're treated is implementation-defined; they'll usually be interpretted relative to your process's current working directory, which is not necessarily the same as the directory your program's executable file lives in. Some operating systems might also provide a single working directory shared by all threads, so you might get unexpected results if a thread changes the working directory at the same time another thread tries to use a relative path.

    0 讨论(0)
提交回复
热议问题