Skip to main content
GameDev.net gamedev.net
🔒 Locked

File Location [C++]

Started by KodeNerd Jul 5, 2008 at 4:43 AM 4 replies 1k views
Original Post
KodeNerd
KodeNerd
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?
------------George Gough
dmatter
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.
KodeNerd
KodeNerd
Thank you.
------------George Gough
Aardvajk
Aardvajk
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
the_edd
the_edd
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).
Mike nl
Mike nl
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.
Million-to-one chances occur nine times out of ten!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.