2011-03-22 3 views
1

현재 프로젝트의 경우 mkdir 기능을 사용하여 디렉토리를 만들어야합니다. 이를 수행하기 위해 현재 디렉토리에 대한 파일 경로가 포함 된 문자열을 생성하기 위해 코드 pwd을 적용하는 데 문제가 있습니다.파일 경로 문자열을 만드는 데 도움이되는 도구

original example code을 수정하여 노드와 문자열을 모두 가져오고 파일 트리를 반복적으로 가로 지르면서 각 단계가 문자열에 기록됩니다. 그런 다음 기본 케이스에 도달하면 문자열이 원래 함수로 반환됩니다. 긴 코드에 대한 죄송합니다

//modified from book, need to get entire file path to create new directories 
char *printpathto(ino_t this_inode, char* name) 
{ 
    ino_t my_inode ; 

    if (get_inode("..") == this_inode) //root points to self 
    return name; 

    chdir("..");    /* up one dir */ 

    // find this dirs actual name 
    if (inum_to_name(this_inode,name,BUFSIZ)) 
    { // 1st: print parent dirs recursively 
     my_inode = get_inode(".");  
     printpathto(my_inode, name); 
    } 

    return name; 
} 

int inum_to_name(ino_t inode_to_find, char *namebuf, int buflen) 
{ 
    DIR  *dir_ptr;  /* the directory */ 
    struct dirent *direntp;  /* each entry */ 

    dir_ptr = opendir("."); 
    if (dir_ptr == NULL){ 
    perror("."); 
    exit(1); 
    } 

    // search directory for a file with specified inum 
    while ((direntp = readdir(dir_ptr)) != NULL) 
    if (direntp->d_ino == inode_to_find) 
     { 
    strncpy(namebuf, direntp->d_name, buflen); 
    namebuf[buflen-1] = '\0'; /* just in case */ 
    closedir(dir_ptr); 
    return 1; 
    } 

    strcpy(namebuf, "???"); // couldn't find it 
    return 0; 
} 

ino_t get_inode(char *fname) 
{ 
    struct stat info; 

    if (stat(fname , &info) == -1){ 
    fprintf(stderr, "Cannot stat "); 
    perror(fname); 
    exit(1); 
    } 

    return info.st_ino; 
} 

내가 디버거를 통해 실행

는, 현재의 디렉토리가 문자열에 표시됩니다 니펫을하지만, SIGABORT가 발생하고 역 추적이 인쇄 될 때 다음 호출이다.

먼저 stdout으로 인쇄하는 대신 원래의 코드를 수정하여 문자열을 반환해야했지만이 백 트레이스 덤프가 왜 발생하는지 잘 모르겠습니다.

아이디어가 있으십니까?

답변

3

getcwd()의 무엇이 잘못 되었나요?

#include <unistd.h> 
#include <stdio.h> 
#include <errno.h> 

int main() { 
    char cwd[1024]; 
    if (getcwd(cwd, sizeof(cwd)) != NULL) { 
     printf("Current working dir: %s\n", cwd); 
     } 
    else { 
     printf("getcwd() error %i",errno); 
     } 
    return 0; 
    } 
+0

그랬습니다. 결과적으로,'getcwd()'는 유닉스 텍스트에는 존재하지 않으며, 클래스에서 다루지도 않았다. 감사! – Jason

+0

@ Jason : 이것이 숙제 인 경우 전체 점은 * getcwd (3) *와 동일한 기능을 구현할 수 있습니다 (예 : 재귀 호출을 수행하는 동안 메모리를 적절하게 관리하고 디렉토리가 inode와 관련되는 방식을 더 잘 이해할 수 있음)). * getcwd (3) *를 사용하면 신용을 얻지 못할 수도 있습니다. –

관련 문제