【发布时间】:2017-05-07 12:23:46
【问题描述】:
我需要创建一个基本上类似于 Linux 上的列表实用程序的程序。我一直在努力让它发挥作用,我已经很接近了,但现在我被卡住了。本质上,它将打印目录中包含的任何文件和子目录(即,如果我运行 ./project3,它会列出该目录中的任何内容)。但是,一旦我尝试让递归调用正常工作,它就会吐出如下内容:
sh: 1: /home/RageKage/Documents/Project3/dir1: Permission denied
这就是我卡住的地方,我不确定从这里该怎么做。我正在获取目录的路径以使用 realpath 进行探索,并且效果很好,但是递归调用不起作用,我不确定自己做错了什么。任何帮助将不胜感激,因为我对此比较陌生。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <limits.h>
int main (int argc, char *argv[])
{
DIR *dir;
struct dirent *sd;
const char *direct;
char buf[PATH_MAX + 1];
if (argc < 2)
{
direct = ".";
}else{
direct = argv[1];
//printf("Hey this is argv[1]: %s\n", argv[1]);
}
dir = opendir(direct);
if (dir == NULL)
{
printf("ERROR! NO DIRECTORY TO OPEN!\n");
exit(1);
}
while( (sd=readdir(dir)) != NULL )
{
if (!strcmp(sd->d_name, ".") || !strcmp(sd->d_name, ".."))
{
}else{
printf("\n>> %s\n", sd->d_name);
}
if (!strcmp(sd->d_name, "..") || !strcmp(sd->d_name, "."))
{
}else if (sd->d_type == 4){
printf("Attempting to Run!\n");
realpath(sd->d_name, buf);
printf("[%s]\n", buf);
system(("./project3 %s", buf));
printf("\n");
}
}
closedir(dir);
return 0;
}
【问题讨论】:
-
递归在哪里?
-
realpath(sd->d_name, buf); system(buf);buf 包含目录的真实路径加上我相信用于启动程序的命令,所以类似于 ./project3 /home/RageKageDocuments/Project3/dir3。至少这是我打印 buf 时得到的结果。 -
真的吗?当你运行这个程序时,你得到的确切输出是什么?
-
我不知道如何发布输出,所以如果有帮助,我就截屏了link
-
这并没有说明
./project3在buf中。
标签: c linux shell directory-structure ls