1

I have a project where I want to read a file with data which lies in a specific folder. I have a script file to execute the program, and this script file can lie anywhere on the computer, hence I cannot use the function getcwd in the program to get the path for my data file. My question is, is there any possibility in C to get the path from where the objective file is located. I.e. not where the script is run from?

Example: Directory of start script: /home/user/my_files/scripts/start_script.sh Directory of main routine: /home/user/project/

Euklides
  • 564
  • 1
  • 10
  • 35
  • How about using an absolute path? – Matthias Feb 25 '13 at 09:49
  • No, that is what I want to come away from. This is a project which could be installed on different computers with different paths. Thus an absolute path would not work. – Euklides Feb 25 '13 at 09:55
  • 2
    If I understand right, you want to know the path of the executed program. This is OS specific, see [here](http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe/1024937#1024937). – Matthias Feb 25 '13 at 11:20

3 Answers3

1

In the script you could do cd <specific dir> and then start the binary using an absolute path.

cd <specific dir>
/home/user/project/main

Then in main you very well could do a getcwd() to have <specific dir> be returned to main.


And no, there is no portable way to get the path where main is located from out of main.

alk
  • 69,737
  • 10
  • 105
  • 255
1

@Matthias has given a link to a question, where the various methods of finding the executable location are well discussed.

I can add one more.

When installing your program, you could embed the path right into the executable file.

For example, in the program you could define an array something like this:

char ExecutablePath[16 + 1024] = "&Unique#!%Stuff~";

where the first 16 characters form a unique sequence not occurring anywhere else in the program and the last 1024 are to contain the path, initially unknown.

During installation you look up this sequence of unique characters in the executable and once it's found you write the path into the file right after it.

You might need to adjust the file's checksum if the OS validates it (Windows doesn't seem to care).

Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180
0

Correct me if I'm wrong, byt looks like you can get away with using the argv[0].

int main(int argc, char** argv)
{
     printf("Name of executable: %s\n", argv[0]);

     /* extract everything before first '/' from argv[0] */
     char buffer[SomeLargeNumber];

     char* ptr = argv[0] + strlen(argv[0]) - 1;

     while(*ptr != '/' && ptr != argv[0]) { ptr--; }

     int len = ptr - argv[0];

     memcpy(buffer, argv[0], len);
     buffer[len] = '/';
     buffer[len + 1] = 0;

     return printf("Directory: %s\n", buffer);
}
Viktor Latypov
  • 14,289
  • 3
  • 40
  • 55