2017-03-06 220 views
0

我正在使用Ubunutu 16.04上的C++程序linux

它是從shell讀取目錄路徑和組的寬度。然後它應該瀏覽目錄並跟蹤文件,如果它發現一個目錄進入並追蹤這些文件。並在年底

如何讓dirent忽略當前目錄?

我有一個奇怪的錯誤會導致一個看似無限循環打印直方圖由於遞歸函數我有一個處理子文件夾。如果我運行比較((J -> d_type) == DT_DIR)其中struct dirent * J。一旦所有文件被讀取,它總是返回true,因爲它會一遍又一遍地調用它自己。

有什麼辦法可以防止這種情況發生?我覺得應該是額外的支票,但我不知道要檢查什麼。我實現它通過一個結構鏈表的結構中的代碼如下:

struct node{ 
    node* next, *prev; 
    int count, name, min, max; 
    node(){ 
     prev = NULL; 
     next = NULL; 
     count = 0; 
     name = nodecount; 
     min = 0; 
     max = 0; 
    } 
} 

;

和源代碼如下:

int main(int argc,char *argv[]){ 
    // Ensures that a valid directory is provided by the cmd line argument 
    if (argc != 3){ 
     fprintf (stderr, "%d is not the valid directory name \n", argc); 
     return 1; 
    } 
    DIR * cwd; // current working directory pointer 
    struct dirent *J; // pointer to dirent struct 
    int binWidth; // variable for the width of the grouping in the histogram 
    binWidth = atoi(argv[2]); 
    node *first = new node; 
    nodecount++; 
    first->max = binWidth - 1; 
    node * current; 
    current = first; 
    bool isadirectory = false; 
    if((cwd = opendir(argv[1]))== NULL){ 
     perror("Can't open directory"); 
     return 2; 
    } 

    while ((J = readdir(cwd)) != NULL){ 
     isadirectory = false; 
     if((J -> d_type) == DT_UNKNOWN){ 
      struct stat stbuf; 
      stat(J->d_name, &stbuf); 
      isadirectory = S_ISDIR(stbuf.st_mode); 
     } 
     else if((J -> d_type) == DT_DIR){ 
      isadirectory = true; 
     } 
     else{ 
      if((J-> d_reclen <= current->max)&&(J->d_reclen >=current->min)){ 
        current->count = current->count+1; 
      } 
      else if(J->d_reclen < current->min){ 
       node*temp = current->prev; 
       while(temp->prev != NULL){ 
        if((J-> d_reclen <= current->max)&&(J->d_reclen >=current->min)){ 
          current->count = current->count+1; 
          break; 
        } 
        else if(J->d_reclen < current->min){ 
         temp = current->prev; 
       } 
      } 
     } 
      else{ 
       nodecount++; 
       current -> next = nextNode(current); 
       current = current -> next; 
      } 
     } 
     if(isadirectory){ 
      traverseNewDirectory(current,J->d_name); 
     } 
    } 
    while ((closedir (cwd) == -1) && (errno == EINTR)); 
    printHistogram(first); 
    return 0; 
} 

回答

1

檢查strcmp(j->d_name, ".") == 0,如果真忽略的目錄。順便說一句,可怕的不好看的名字,j

+1

忽略'strcmp(j-> d_name,「..」)== 0'的情況可能也是一個好主意。 –

+0

你們都是對的。對於不具名的var名稱感到抱歉。我的創造力在清晨時分開始流行。我會考慮重構的。 – Callat