gpt4 book ai didi

c++ - 如何让 dirent 忽略当前目录?

转载 作者:行者123 更新时间:2023-11-28 01:52:07 26 4
gpt4 key购买 nike

我正在 Ubunutu 16.04 linux 上开发一个 C++ 程序

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

我有一个奇怪的错误,由于我有处理子文件夹的递归函数,它导致看似无限循环。如果我运行比较 ((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;
}

最佳答案

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

顺便说一下,j 这个名字太难描述了。

关于c++ - 如何让 dirent 忽略当前目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42618597/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com