Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

c++ - How to use fstream objects with relative path?

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 such as project path?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use relative paths as well. But they are relative to the environment you call your executable from.

This is OS dependent but all the major systems behave more or less the same AFAIK.

Windows example:

// File structure:
c:foldermyprogram.exe
c:myfile.txt

// Calling command from folder
c:folder > myprogram.exe

In the above example you could access myfile.txt with "c:/myfile.txt" or "../myfile.txt". If myprogram.exe was called from the root c: only the absolute path would work, but instead "myfile.txt" would work.

As Rob Kennedy said in the comments there's really nothing special about paths regarding fstream. But here is a code example using a relative path:

#include <fstream>
int main() {
    std::ifstream ifs("../myfile.txt");
    ... // Do something sensible with the file
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...