# File Location [C++]

## Recommended Posts

Does std::ifstream open files relative to the executable or not? If not, is there any way I can find out the location of the executable at runtime?

##### Share on other sites
Quote:
 Original post by KodeNerdDoes std::ifstream open files relative to the executable or not?

It does.
Not that I've ever tried, but I'm pretty sure you could give it an absolute path too.

Thank you.

##### Share on other sites
On Windows, to get the path of the executable:

#include <windows.h>void f(){    char c[MAX_PATH];            GetModuleFileName(GetModuleHandle(NULL),c,MAX_PATH);}

This returns the full path to the executable, including the exename. You can then use std::string and the find_last_of() method to strip out the path:

#include <windows.h>#include <string>std::string ExecutablePath(){    char c[MAX_PATH];    GetModuleFileName(GetModuleHandle(NULL),c,MAX_PATH);    std::string S=c;    return S.substr(0,S.find_last_of("\\/"))+"\\";}

HTH

##### Share on other sites
Quote:
Original post by dmatter
Quote:
 Original post by KodeNerdDoes std::ifstream open files relative to the executable or not?

It does.
Not that I've ever tried, but I'm pretty sure you could give it an absolute path too.

This is incorrect.

It does not unless your current working directory happens to be the same as the executable directory.

Files are sought starting in the current working directory.

For example, if you run C:\a\prog.exe from C:\b\, files will be sought relative to C:\b\ (if you give a relative path).

##### Share on other sites
Formally, this is implementation-defined.

ISO C++ 27.8.1.3:
Quote:
 ... It then opens a file, if possible, whose name is the NTBS s ("as if" by calling std::fopen(s,modstr)).

ISO C 7.19.3.8:
Quote:
 Functions that open additional (nontemporary) files require a file name, which is a string. The rules for composing valid file names are implementation-defined.

C/C++ doesn't have the notion of directories.

But practically, yes; on *NIX and Windows non-absolute file paths are relative to the current directory.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628345
• Total Posts
2982193

• 9
• 24
• 10
• 9
• 13