【发布时间】:2020-01-29 05:17:07
【问题描述】:
我正在尝试将目录中的文件列出到用户指定的特定级别。
我面临的主要问题是我认为子目录不被识别为目录。因此,我尝试将字符串附加到目录的上层。但它似乎不起作用。
这里是使用 ls -R 生成的目录结构(所有 dir* 都是目录):
dir1 dir2 dir3 listDirectory listDirectory.c
./dir1:
dir1.1 dir1.2 dir1.3
./dir1/dir1.1:
dir1.1.1
./dir1/dir1.1/dir1.1.1:
./dir1/dir1.2:
./dir1/dir1.3:
./dir2:
dir2.1 dir2.2 dir2.3
./dir2/dir2.1:
./dir2/dir2.2:
./dir2/dir2.3:
./dir3:
代码如下:
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <regex.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
struct stat s;
regex_t regex;
const char *expression = "^[.]*$";
int reti;
//Directory listing main loop
int listDirectory(int counter,int level,char arr[200]){
printf("Here Counter = %d and Level = %d\n", counter, level);
//Check if the counter is equal to level. If yes exit
if(counter >= level){
return 0;
}
char *currentDirctory = arr;
// printf("%s\n",currentDirctory);
struct dirent *de; // Pointer for directory entry
DIR *dr = opendir(currentDirctory); // opendir() returns a pointer of DIR type.
if (dr == NULL) // opendir returns NULL if couldn't open directory
{
printf("Could not open current directory");
return 0;
}
//Read the contents of the directory
while ((de = readdir(dr)) != NULL){
int size = 0;
struct stat statbuf;
char *x = de->d_name; //The name of each file or folder
char c2[100];
strcpy(c2,x);
strcpy(arr,c2);
//Replace the content of arr with that of new directory or file name
reti = regexec(®ex, arr, 0, NULL, 0);
//Check if the file doesn't match . or .. which is the parent and grand-parent directory
if(!reti){
//If it matches check for next file
continue;
}
else if(reti == REG_NOMATCH){
printf("%s\n",arr);
//Check if the file or the path is a direcfory
stat(arr, &statbuf);
if(S_ISDIR(statbuf.st_mode)){
//If it is a directory then increase the counter and size and put the directory in loop for next call
counter += 1;
listDirectory(counter,level, arr);
size += 1;
}
else{
//It is a file check for next file
continue;
}
counter -= size;
}
}
closedir(dr);
}
int main(){
char arr[200] = "./";
reti = regcomp(®ex, expression, 0);
if(reti) {
fprintf(stderr, "Could not compile regex\n");
}
listDirectory(0,2,arr);
return 0;
}
输出是:
Here Counter = 0 and Level = 2
dir3
Here Counter = 1 and Level = 2
listDirectory.c
dir1
Here Counter = 1 and Level = 2
dir1.1
dir1.3
dir1.2
listDirectory
dir2
Here Counter = 1 and Level = 2
dir2.3
dir2.2
dir2.1
但应该是:
Here Counter = 0 and Level = 2
dir3
Here Counter = 1 and Level = 2
listDirectory.c
dir1
Here Counter = 1 and Level = 2
dir1.1
Here Counter = 2 and Level = 2
dir1.1.1
dir1.2
listDirectory
dir2
Here Counter = 1 and Level = 2
dir2.3
dir2.2
dir2.1
【问题讨论】:
-
输出中的目录和文件是什么?请提供
tree或至少在示例输出中显示文件和目录布局的列表是dir1.1.1文件或目录? (其余相同)如果您位于示例目录的顶层,请发布输出tree。 -
我已经更新了目录结构的问题。
标签: c pointers recursion directory file-handling