0

I am trying to get the current running file name in C++. I wrote a simple code that uses both argv[0] and boost current_path() method. The file is compiled into executable file mainWindow.

#include "boost/filesystem.hpp"

int main(int argc, char* argv[])
{
    boost::filesystem::path full_path( boost::filesystem::current_path() );
    std::cout << full_path.string() << "\n";

    std::cout << argv[0] << "\n\n";

    return 0;
} 

Interestingly the output of each method is different.

argv[0] output is:

../VENTOS/src/loggingWindow/mainWindow

current_path() output is:

/home/mani/Desktop/VENTOS_Redpine

I am not running my program (mainWindow) directly from the terminal. Another application is calling my program and I guess that's why the output is different. Am I right on this?

My second question is: Without using the argv[0] option and relying only on the boost filesystem methods, how can I get the same result as argv[0]?

ManiAm
  • 1,759
  • 5
  • 24
  • 43

1 Answers1

3

argv[0] only contains the command used to execute the the program. This may contain the path. It may contain a relative path. It may contain no path at all. It might not even contain the executable name thanks to symlinks etc.... It might even be empty if the hosting system chooses to provide nothing. It can't be trusted, so you don't want to use this as a basis for evaluating other methods.

boost::filesystem::current_path fails you because it only returns the current working directory. This may or may not be the location of the executable because it depends on the directory from which the program was run and whether or not the working directory has been changed by the program. To be honest I'm not sure if there is a sure-fire way to get the process name and path from Boost. There wasn't a few years ago, but time has a way of marching on, you know?

There are a slew of questions covering how to get the executable and path (Finding current executable's path without /proc/self/exe looks promising but is stale. That time marching thing again.) but all are platform-specific you may have to do some ifdef or linker wizardry to make this work.

Community
  • 1
  • 1
user4581301
  • 33,082
  • 7
  • 33
  • 54