File Location [C++]

Started by
4 comments, last by Mike nl 15 years, 10 months ago
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
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.
Thank you.
------------George Gough
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
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).
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!

This topic is closed to new replies.

Advertisement