Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 417
user336359 Avatar asked Nov 09 '11 17:11

user336359


People also ask

Does Ifstream use relative path?

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.

What is a relative path?

A relative path refers to a location that is relative to a current directory. Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy.


Video Answer


1 Answers

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:\folder\myprogram.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 } 
like image 81
Kleist Avatar answered Oct 13 '22 03:10

Kleist