源代碼如下:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#define DEPTH 100
#define MYHOME "/home/yaodl"
#define NAME "abcdedfhighkelsmgskdiskcjsieksksjdkslsjdlsls"
#define MAXSIZE 8192
int main(int argc,char **argv)
{
int i,size;
char *path;
if(chdir(MYHOME) < 0){
fprintf(stderr,"chdir error!\n");
exit(-1);
}
for(i=0;i<DEPTH;i++){
if(mkdir(NAME,DIR_MODE) < 0){
printf("mkdir failed,i = %d\n",i);
exit(-1);
}
if(chdir(NAME) < 0){
printf("chdir failed,i = %d\n",i);
exit(-1);
}
}
if(creat("afile",FILE_MODE) < 0){
printf("create error!\n");
exit(-1);
}
/*
* The deep directory is created,with a file at the leaf.
* Now Let's try to obtain its pathname.
*/
path = (char *)malloc(1024);
for(;;){
if(getcwd(path,size) != NULL){
break();
}
else{
printf("getcwd faied,size = %d",size);
size += 100;
if(size > MAXSZ){
printf("giving up!\n");
exit(-1);
}
if((path = realloc(path,size)) == NULL){
printf("realloc error!\n");
exit(-1);
}
}
}
printf("length = %d\n%s\n",strlen(path),path);
exit(0);
}