0

I'm not sure how to ask this, but I'll do my best. Anyway, my situation is this: I have files that I want my app/executable to be able to access at all times that are relative to the executable's path or in the same directory as the program. Since I want my program to be able to run in any CWD and still get everything it needs. I want to know what's the best way or method to get a file that's relative to my executable, that won't mess up the user's CWD?

The approach I had in my head is this:

  1. Get program's directory using OS dependent function.
  2. Use some string manipulation to get the program's home directory.
  3. Append to the string the file I require during run time without having to use any hat trick CWD commands.

Not sure if Windows/Linux already has something up it's sleeves to deal with this, but I thought I should know if there is a better alternative.

Thank you!

ajm113
  • 936
  • 1
  • 8
  • 18

1 Answers1

-1

If the files, that you want to access from your C binary, are in the same directory or subdirectory, you can access directly by using ".", this is the current directory.

or you can simply use the getwd function.

char *getwd(char *buf);

Typically, you can use like this (this snippet will print you, the current directory of the C binary):

int main()
{       
 char buf[4096];
 getwd(buf);
 printf(but);
}
  • But what if my binary is being called outside of the directory of where the binary is being stored in terminal? i.e app being stored in /etc/bin/, but it's being executed in the user's home folder. How would I fetch a config file or something that's in the app's folder? – ajm113 Aug 15 '16 at 19:56