我面临一个奇怪的问题,昨晚我正在做我的作业ls
linux
,代码在那里工作正常,现在当我在imac上测试时,它不起作用。它只读取当前目录,它不包含子目录。
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#define GREEN "\x1b[32m"
#define BLUE "\x1b[34m"
#define WHITE "\x1b[37m"
void Usage() {
fprintf(stderr, "\nUsage: exec [OPTION]... [DIR]...\n");
fprintf(stderr, "List DIR's (directory) contents\n");
fprintf(stderr, "\nOptions\n-R\tlist subdirectories recursively\n");
return;
}
void RecDir(char * path, int flag) {
DIR * dp = opendir(path);
if(!dp) {
perror(path);
return;
}
struct dirent * ep;
char newdir[512];
printf(BLUE "\n%s :\n" WHITE, path);
while((ep = readdir(dp)))
if(strncmp(ep->d_name, ".", 1))
printf(GREEN "\t%s" WHITE, ep->d_name);
closedir(dp);
dp = opendir(path);
while((ep = readdir(dp))) if(strncmp(ep->d_name, ".", 1)) {
if(flag && ep->d_type == 4) {
sprintf(newdir, "%s/%s", path, ep->d_name);
RecDir(newdir, 1);
}
}
closedir(dp);
}
int main(int argc, char ** argv) {
switch(argc) {
case 2:
if(strcmp(argv[1], "-R") == 0)
Usage();
else
RecDir(argv[1], 0);
break;
case 3:
if(strcmp(argv[1], "-R") == 0)
RecDir(argv[2], 1);
else
Usage();
break;
default:
Usage();
}
return 0;
}
答案 0 :(得分:0)
标志变量始终为0
所以我在调用RecDir()
函数时更改了它,以便它进入if块:
if(flag && ep->d_type == 4) {
sprintf(newdir, "%s/%s", path, ep->d_name);
printf("here: %s\n",ep->d_name);
RecDir(newdir, 1);
}
并且能够递归调用RecDir()
函数。
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#define GREEN "\x1b[32m"
#define BLUE "\x1b[34m"
#define WHITE "\x1b[37m"
void Usage() {
fprintf(stderr, "\nUsage: exec [OPTION]... [DIR]...\n");
fprintf(stderr, "List DIR's (directory) contents\n");
fprintf(stderr, "\nOptions\n-R\tlist subdirectories recursively\n");
return;
}
void RecDir(char * path, int flag) {
DIR * dp = opendir(path);
if(!dp) {
perror(path);
return;
}
struct dirent * ep;
char newdir[512];
printf(BLUE "\n%s :\n" WHITE, path);
while((ep = readdir(dp)))
if(strncmp(ep->d_name, ".", 1))
printf(GREEN "\t%s" WHITE, ep->d_name);
closedir(dp);
dp = opendir(path);
while((ep = readdir(dp))) if(strncmp(ep->d_name, ".", 1)) {
//printf("In While %d\n",flag);
if(flag && ep->d_type == 4) {
sprintf(newdir, "%s/%s", path, ep->d_name);
printf("here: %s\n",ep->d_name);
RecDir(newdir, 1);
}
}
closedir(dp);
}
int main(int argc, char ** argv) {
switch(argc) {
case 2:
if(strcmp(argv[1], "-R") == 0)
Usage();
else
//supplied flag=1 instead of 0, explained above.
RecDir(argv[1], 1);
break;
case 3:
if(strcmp(argv[1], "-R") == 0) {
RecDir(argv[2], 1);
}
else
Usage();
break;
default:
Usage();
}
return 0;
}
答案 1 :(得分:0)
鉴于它是另一个操作系统,您首先需要确认d_type
保存您认为它的值。在第一个循环中,作为调试,打印出d_type
以及名称。
请注意,在第二个循环中,您第二次扫描目录以进入子目录时会遇到很多麻烦 - 然后在最后一秒决定不{i}
flag
是0
。为什么不对flag
预先测试0
而根本不再执行整个打开目录呢?