A. K.
A. K.

Reputation: 38270

finding out the path to a file at runtime

In a program I open a file say file.dat at runtime. The problem is when i run the executable it expects the file to be in the directory from where it is executed. I want the program to look into the same directory where the executable is present. What modifications should I make in my program (or in the build system).

For example consider this program:

int main()
{
std::ifstream ip("file.dat");
// do something.


return 0;
}

I am working on Ubuntu with g++-4.6 compiler and CMake build system. Since the project supports out-of-source build that means the program executable can be anywhere depending upon the directory where the cmake was invoked from.

Thanks for the help...

Upvotes: 3

Views: 447

Answers (2)

cellcortex
cellcortex

Reputation: 3176

On Linux reading /proc/self/exe is the best way to go.

  char app_path[1024];
  ssize_t len = ::readlink("/proc/self/exe", app_path, sizeof(app_path)-1);
  if (len != -1) {
    app_path[len] = '\0';
  } else {
    // handle error
  }

For other OS, see: https://stackoverflow.com/a/1024937/105015

Upvotes: 1

jxh
jxh

Reputation: 70502

On many systems, the argv[0] parameter will have the path used to execute the program. Whether or not this is the full path of the program depends on how it was invoked.

int main (int argc, char *argv[]) {
    std::string progname(argv[0]);
    std::string datafile;
    if (progname.find_last_of('/') != std::string::npos)
        datafile = progname.substr(0, progname.find_last_of('/')+1);
    datafile += "file.dat";
    std::ifstream ip(datafile.c_str());
    //...
}

Upvotes: 1

Related Questions