开发者

Win API Local File Reference c++

I am trying to hard code into C++ program to look for config.ini in the same directory 开发者_StackOverflow中文版as the executable, without knowing the complete path to the file. I am trying to find a way to make a local reference to the executable.

Basically load ("./config.ini") without doing

("C:\foo\bar\config.ini")


There isn't really any guaranteed portable way of doing this, but I like to use this code because it works in the vast majority of cases (unless symlinks or other magic is involved):

boost::filesystem::current_path(boost::filesystem::path(argv[0]).remove_filename());

If you are willing to use platform specific code look at GetModuleFileName on Windows and a mix of getpid, reading from /proc and readlink on Linux.


You want GetModuleFilename() on Windows (pass NULL to get filename of current executable). Otherwise, call boost::filesystem::initial_path() early in the program (see Boost docs in link for the reason to do this early). That should cover most of the situations.

Edit

Brain malfunction. We always start our programs from the executable's directory, so the boost::initial_path() thing works, but it won't work so well if you start the program from another direcory. Sorry for the confusion on that. On Windows, though, I'd get the path from GetModuleFilename and use boost::path to manipulate the result.


For windows, this will get the directory containing the excutable as a c++ string:

#include <windows.h>
#include <string>
#include <iostream>
using namespace std;;

string ExePath() {
    char buffer[MAX_PATH];
    GetModuleFileName( NULL, buffer, MAX_PATH );
    string::size_type pos = string( buffer ).find_last_of( "\\/" );
    return string( buffer ).substr( 0, pos);
}

You can then just tag the name of your config file on the end.


For Windows:

#include <direct.h>

char cur_path[FILENAME_MAX];

if (!_getcwd(cur_path, sizeof(cur_path)))
{
    // deal with error
}

cur_path[sizeof(cur_path) - 1] = '/0'; // adding \0 at the end of the string

printf("Current dir: %s", cur_path);

A platform-agnostic solution was discussed here:

How do I get the directory that a program is running from?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜