1.使用getcwd()获取的是当前工作路径,而不一定是程序的路径
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXBUFSIZE 1024
int main ( int argc, char * argv[] )
{
char buf[ MAXBUFSIZE ];
getcwd(buf, MAXBUFSIZE);
printf("\n");
printf(buf);
printf("\n");
return 0;
}
2.下面这个是一个 x86_64 GNU/Linux Kernel 3.2.0-67-generic 系统中利用proc获取绝对路径的例子,利用 readlink()
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXBUFSIZE 1024
int main ( int argc, char * argv[] )
{
char buf[ MAXBUFSIZE ];
int count;
count = readlink( "/proc/self/exe", buf, MAXBUFSIZE );
if ( count < 0 || count >= MAXBUFSIZE )
{
printf( "Failed\n" );
return( EXIT_FAILURE );
}
buf[ count ] = '\0';
printf( "/proc/self/exe -> [%s]\n", buf );
return( EXIT_SUCCESS );
}