#include <stdio.h> #include <string.h> #include <stdlib.h> main(int argc, char **argv) { char *bufP=malloc(128); strcpy(bufP,(char *)argv[1]); printf("dir=%s/n",bufP); printf("argv[1]=%s/n",(char *)argv[1]); char *ROOT=malloc(256); memset(ROOT,0,256); printf("%s/n",dirname(bufP)); printf("%s/n",bufP); }
gcc -o a a.c
执行:
./a /home/www/socketchat/gm11.txt
结果:
dir=/home/www/socketchat/gm11.txt
argv[1]=/home/www/socketchat/gm11.txt
/home/www/socketchat
/home/www/socketchat
总结:dirname应该会将结果存出传入的参数当中,传入的参数必须分配内存,不能是常量
再来一个,取得当前运行的程序的位置的代码:
#include <stdio.h> #include <string.h> #include <stdlib.h> main(){ char bufP[256],ROOT[256]; char resolved_path[256]; memset(bufP,0,256);printf("%d/n",__LINE__); sprintf(resolved_path,"/proc/%d/exe",getpid()); readlink(resolved_path,bufP,256);printf("%d/n",__LINE__); //printf("resolved_path=%s/n",resolved_path); //printf("bufP=%s/n",bufP); memset(ROOT,0,256); strcpy(ROOT,bufP); dirname(ROOT); printf("%s/n",ROOT); }