• Advertisement
Sign in to follow this  

File Location [C++]

This topic is 3520 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by KodeNerd
Does 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.

Share this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by dmatter
Quote:
Original post by KodeNerd
Does 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 this post


Link to post
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement