[英]How to get dirent to ignore current directory?
I am working on a C++ program on Ubunutu 16.04 linux 我正在Ubunutu 16.04 linux上开发C ++程序
It is to read a directory path and group width from shell. 它是从外壳读取目录路径和组宽度。 It should then navigate through the directory and keep track of files, if it finds a directory go in it and track those files as well.
然后,如果它找到目录并跟踪这些文件,则应浏览目录并跟踪文件。 And print a histogram at the end
并在最后打印直方图
I have an odd bug that causes a seemingly infinite loop due to the recursive function I have that handles sub folders. 我有一个奇怪的错误,由于我拥有处理子文件夹的递归函数,导致了看似无限的循环。 If I run the comparison
((J -> d_type) == DT_DIR )
where struct dirent*J. 如果我运行比较
((J -> d_type) == DT_DIR )
,则结构dirent * J。 It always returns true once all the files are read because it calls itself over and over again. 读取所有文件后,它总是返回true,因为它会一遍又一遍地调用自身。
Is there any way to prevent that? 有什么办法可以防止这种情况? I feel like an extra check should be all that I need but I don't know what to check.
我觉得应该多做一张支票,但我不知道要检查什么。 I implemented it via a struct linked list the code for the struct is below:
我通过结构链接列表实现了该结构的代码如下:
struct node{
node* next, *prev;
int count, name, min, max;
node(){
prev = NULL;
next = NULL;
count = 0;
name = nodecount;
min = 0;
max = 0;
}
}
; ;
And the source code is as follows: 源代码如下:
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;
}
Check for strcmp(j->d_name, ".") == 0
and ignore the directory if true. 检查
strcmp(j->d_name, ".") == 0
,如果为true,则忽略目录。
Horribly undescriptive name, j
, by the way. 顺便说一下,名称
j
令人难以置信。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.