Sign in to follow this  
KodeNerd

File Location [C++]

Recommended Posts

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this