2017-03-06 214 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