我必须在C语言的Linux上用DOS实现 tree 命令,这样当我在目录中运行./tree时,它就像这样输出:
adir
bdir
cdir
d.java
edir
fdir
g.c
hdir
我当前的代码看起来像这样,但是当我运行它时它甚至都没有终止,但我不知道如何修复它。请帮我解决一下!
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#define MAXLEN 256
char currentDir[256];
const char *pathname;
void tree(DIR *dp, struct dirent *dp1, char currentDir[256], int spaces);
void treeHelper(DIR *dp, struct dirent *dp1, char currentDir[256], int spaces);
int main(int argc, char* argv[]) {
DIR *dp = opendir(".");
struct dirent *dp1 = readdir(dp);
int spaces = 0;
//char currentDir[256];
getcwd(currentDir, sizeof(currentDir));
while(dp1 != NULL) {
if (strcmp(dp1->d_name, ".") == 0 || strcmp(dp1->d_name, "..") == 0) {
continue;
}
if (dp1->d_type == DT_REG) {
printf("%s\n", dp1->d_name);
}
if (dp1->d_type == DT_DIR) {
tree(dp, dp1, currentDir, spaces);
}
}
closedir(dp);
}
void tree(DIR *dp, struct dirent *dp1, char currentDir[256], int spaces) {
int i = 0;
strcat(currentDir, "/");
strcat(currentDir, dp1->d_name);
if((chdir(currentDir)) == -1){
chdir("..");
getcwd(currentDir, sizeof(currentDir));
strcat(currentDir, "/");
strcat(currentDir, dp1->d_name);
for(i = 0; i < spaces; i++) {
printf (" ");
}
printf("%s (subdirectory)\n", dp1->d_name);
spaces++;
treeHelper(dp, dp1, currentDir, spaces);
}
else {
for(i = 0; i < spaces; i++) {
printf(" ");
}
printf("%s (subdirectory)\n", dp1->d_name);
chdir(currentDir);
spaces++;
treeHelper(dp, dp1, currentDir, spaces);
}
}
void treeHelper(DIR *dp, struct dirent *dp1, char currentDir[256], int spaces) {
int i = 0;
while((dp1 = readdir(dp)) != NULL){
if(strcmp(dp1->d_name, ".") == 0 || strcmp(dp1->d_name, "..") == 0)
continue;
//stat(currentPath, &statbuf);
/*if(dit->d_type == 8 && argv[1] != NULL){*/
if(dp1->d_type == DT_REG){
for(i = 0; i < spaces; i++) {
printf(" ");
}
printf("%s\n", dp1->d_name);
}
/*if(dit->d_type == 4)*/
if(dp1->d_type == DT_DIR)
tree(dp, dp1, currentDir, spaces);
}
}
谢谢!
答案 0 :(得分:1)
我当前的代码看起来像这样,但是当我没有时,它甚至都没有终止 跑吧......
struct dirent *dp1 = readdir(dp); … while(dp1 != NULL) {
您只需拨打readdir()
一次,然后一次又一次地在同一 dirent 上进行无限循环操作。将其更改为
struct dirent *dp1;
…
while (dp1 = readdir(dp))
{