如何让dirent忽略当前目录?

时间:2017-03-06 06:05:07

标签: c++ file ignore

我正在研究Ubunutu 16.04 linux上的C ++程序

它是从shell读取目录路径和组宽度。然后它应该在目录中导航并跟踪文件,如果它找到了一个目录并且也跟踪这些文件。并在末尾打印直方图

由于我处理子文件夹的递归函数,我有一个奇怪的错误导致看似无限循环。如果我运行struct ((J -> d_type) == DT_DIR ) where 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 个答案:

答案 0 :(得分:2)

检查strcmp(j->d_name, ".") == 0并忽略该目录,如果为真。

顺便说一句,名字不大,j