Käptn Freiversuch
Käptn Freiversuch

Reputation: 268

C++ fopen relative Path

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.

Upvotes: 7

Views: 32795

Answers (2)

user4815162342
user4815162342

Reputation: 155046

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.

Upvotes: 8

localhost
localhost

Reputation: 373

@Käptn With some modifications to the code, due to some warnings encountered, I found the following worked, although I used the C drive and not D drive as my system does not have a D drive. Effectively, the following code works same and my system will have the "file opened" message that I have added. I find this works the same whether it is run through the debugger, or executed directly from the executable in the Debug folder.

Paths

Here is my .exe file C:\uni\c++\ex5\msvc2013\ex5\Debug    
Here is the file i want to read C:\uni\c++\ex5\res\thehead.raw

Source Code

#include <iostream>

int main (int argc, char ** argv)
{
    FILE* f;
    fopen_s(&f, "..\\..\\..\\res\\thehead.raw", "rb");
    if (f == NULL)
    {
        printf("FAIL!!");
    }
    else
    {
        printf("File opened.");
    }
    return 0;
}

Upvotes: 3

Related Questions