Page 1 of 1

Is this a "safe" way to get the current path?

Posted: Sat Feb 10, 2007 8:47 pm
by earlz
I have been working on getting a platform independent way to get the current path

right now to get the path of what was called I do this:

Code: Select all

void GetOpen86Dir(char *arg){ //arg is argv[0]
    char *end=arg+strlen(arg);
    while(arg<end){
        if(*end=='/' || *end=='\\'){
            end++; //save the '/'
            *end='\0';
            strcpy(open86_dir,arg);
            return;
            }
        end--;
    }
    strcpy(open86_dir,"");
    printf("Warning!! Cannot figure out open86's directory--so using \'./\'");
}
}
basically what that does is scan the argv[0] from it's end until it finds a / or \, and upon finding that it adds a \0 to it to null terminate it and then copies it to my open86_dir pre-allocated string

now, is this a safe way to obtain the path? in some OS's will it fail?(it works in windows, and haven't tested it anywhere else)

Posted: Sat Feb 10, 2007 10:03 pm
by Alboin
When I run this:

Code: Select all

int main(int argc, char * argv[], char *envp[]) {
	printf("Path: %s\n", argv[0]);
}
I get this result:

Code: Select all

Path: ./p
Uhh, I'm on Linux.....Am I doing something wrong?

Posted: Sun Feb 11, 2007 4:15 am
by Solar
No, you aren't doing anything wrong. Quoting the C standard, chapter 5.1.2.2.1 "Program startup":
— If the value of argc is greater than zero, the array members argv[0] through
argv[argc-1] inclusive shall contain pointers to strings, which are given
implementation-defined values by the host environment prior to program startup. The
intent is to supply to the program information determined prior to program startup
from elsewhere in the hosted environment. If the host environment is not capable of
supplying strings with letters in both uppercase and lowercase, the implementation
shall ensure that the strings are received in lowercase.
— If the value of argc is greater than zero, the string pointed to by argv[0]
represents the program name; argv[0][0] shall be the null character if the
program name is not available from the host environment. If the value of argc is
greater than one, the strings pointed to by argv[1] through argv[argc-1]
represent the program parameters.
Read, the things written into argv are implementation-defined. All bets are off as to whether argv[0] contains an absolute or relative path, or any path at all. Besides, the current directory need not be the same as the program's directory. Paths are platform-dependent, so there is no way to determine them platform-independantly.

Posted: Sun Feb 11, 2007 9:03 am
by Brendan
Hi,

If you're willing to accept "compiler dependant" code that is platform independant, then GCC's libraries have "get_current_dir_name()", "getwd()", "getcwd()", "basename()" and "dirname()' - all of which might help...


Cheers,

Brendan