Sunday 20 November 2011

How can I determine which directory my program is running from? in C programmin

How can I determine which directory my program is running from?

Fortunately for us DOS programmers, the DOS program loader provides the full pathname of the executable file when it is run. This full pathname is provided via the argv[0] pointer, which is pointed to by the argv variable in your main() function. Simply strip off the name of your program, and you have the directory from which your application is running. A bit of example code demonstrates this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main(int argc, char ** argv)
{
char execDir[80];
int i, t;
/* set index into argv[0] to slash character prior to appname */
for(i = (strlen(argv[0]) - 1);
( (argv[0][i] != ‘/’) && (argv[0][i] != ‘\\’) ); --i);
/* temporarily truncate argv[] */
t = argv[0][i];
argv[0][i] = 0;
/* copy directory path into local buffer */
strcpy(execDir, argv[0]);
/* put back original character for sanity’s sake */
argv[0][i] = t;
}

Cross Reference:

XX.1: How are command-line parameters obtained?

No comments:

Post a Comment