Skip to content
Advertisement

C++ get source file directory in Linux

This question is many time asked and I referred all, but I need bit different.

I am using macbook -> Clion (IDE) for C++ My program file location /Users/Kandarp/ClionProjects/SimulationParser/main.cpp

When I use following function for get current directory it gives different file (I think actual path where file is compiled and execute)

string ExePath() {
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
    fprintf(stdout, "Current working dir: %sn", cwd);
    return cwd;
} else {
    perror("getcwd() error");
    return 0;
}}

it gives following answer: /Users/Kandarp/Library/Caches/CLion2016.2/cmake/generated/SimulationParser-50b8dc0e/50b8dc0e/Debug

But I need path where my .cpp file reside.What I am doing wrong ? Please help

Advertisement

Answer

You’re doing nothing wrong.

getcwd() gives you the current directory of the executing process.

When you instruct whatever tool you’re using to build your C++ code to run it, it simply runs the process from that directory.

There is nothing in the C++ library that tells the application the location of its source code.

If you need your application to know where its source code lives, you need to pass that either as an argument to main(), or put it into some configuration file, that your application reads, or any similar approach.

Advertisement