怎样判断正在运行的C语言程序所在的目录?
我们这些DOS程序员是很幸运的,因为DOS程序的装入程序会提供正在运行的可执行文件的路径全名。这个路径全名是通过指针argv[0]提供的,mai‘n()函数的argv变量指向该指针。只需去掉路径全名中的文件名,你就得到了正在运行的程序所在的目录。下面的例子演示了这种技巧:
# 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[O][i] ! ='/' ) && (argv[O][i]! =' \\' ));--i) ;
/ * temporarily truncate argv[] * /
t =argv[O][i] ;
argv[O][i]= O ;
/ * copy directory path into local buffer * /
strcpy(execDir ,argv[O]) ;
/* put back original character for sanity's sake * /
argvEO]Ei]=t;
}
# 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[O][i] ! ='/' ) && (argv[O][i]! =' \\' ));--i) ;
/ * temporarily truncate argv[] * /
t =argv[O][i] ;
argv[O][i]= O ;
/ * copy directory path into local buffer * /
strcpy(execDir ,argv[O]) ;
/* put back original character for sanity's sake * /
argvEO]Ei]=t;
}