PDA

View Full Version : Relatives Paths and argc/argv




kainjow
Aug 25, 2006, 03:07 PM
What's the best way to handle relative paths passes as parameters to a program, accessed with argc/argv?

For example, I've got a script program named "bob" that takes a parameter for a file with a picture:
./bob mypic.jpg
What's the best way to access mypic.jpg?

Also, I realize that when the script is executed as a relative or full path (i.e. "./bob" or "/Users/me/bob") I can just read argv[0] for the script's name, but what if it's located in /usr/bin and it's run just by "bob" - how is the path of program found then?



MarkCollette
Aug 25, 2006, 05:40 PM
Every program run has access to an environment variable called "CWD" which stands for current working directory. When using the methods for openning a file, that are provided by the standard C/C++ libraries, if you pass them a relative path they will know to check this variable, and concatenate the two to form the absolute path. So basically, an application need not worry about absolute or relative paths itself, since it's handled for you. The current working directory would be described as the directory your shell has you in, and is in no way related to the path that the binary executable is at.

kainjow
Aug 25, 2006, 05:59 PM
Cool, yeah I got it figured it out. I just used getcwd() and then added the path of the file passed (if it was relative) and used that. Normally I wouldn't have had this problem but the program has to use files that are located in its parent directory.

MarkCollette
Aug 25, 2006, 06:29 PM
Cool, yeah I got it figured it out. I just used getcwd() and then added the path of the file passed (if it was relative) and used that. Normally I wouldn't have had this problem but the program has to use files that are located in its parent directory.

Do you mean that the files are in the parent directory to CWD, or the parent directory to where the executable is located?

And do you mean that you're trying to interpret relative paths as being relative to something else than CWD?

kainjow
Aug 25, 2006, 06:50 PM
The files are in the parent directory of where the executable is located. In the code I change directories to deal with some temporary files, so that also screwed up the relative paths. But I converted the relative paths to absolute paths and got it all sorted out now.

Fairly
Sep 24, 2006, 06:31 PM
I don't see the issue here. This is what all command line tools do. They don't worry about where the files are located - you have to.

If your CWD isn't right, then it won't work. But don't worry about the program's CWD - worry about your own. Unless I'm off track here, it's a lot simpler than you think.