Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ fopen relative Path

Tags:

c++

windows

I read through some topic about relative path, but i still got i wrong. I hope sb can help me :). I am using Visual studio 2013, windows 7

I got the following directories:

Here is my .exe file D:\uni\c++\ex5\msvc2013\ex5\Debug

Here is the file i want to read D:\uni\c++\ex5\res\thehead.raw

The code for opening the file:

FILE* f;
f = fopen("..\\..\\..\\res\\thehead.raw", "rb");
if (f == NULL)
printf("FAIL!!");

As i need to use relative paths i figured it out as following: ..\ gets to parent directory.

so "..\..\..\" should get me into the folder "D:\uni\c++\ex5\".

\res should open the res foulder.

Needless to say it fails and i have no idea why. Any help would be appreciated.

like image 956
Käptn Freiversuch Avatar asked Jul 06 '14 14:07

Käptn Freiversuch


Video Answer


1 Answers

Relative paths are relative to the current working directory, not the path of the executable. The current working directory is the directory from which you started the program.

To treat a path as relative to the position of the executable, the simplest portable option is to access the executable as argv[0], extract the directory, and chdir() into it. Note that this will work only as long as the program was itself started with the full path name.

like image 85
user4815162342 Avatar answered Oct 12 '22 08:10

user4815162342