linux c 关于目录打印的例子,运行结果有有关问题
linux c 关于目录打印的例子,运行结果有问题
求解释,分数不多,见谅!
------解决方案--------------------
第11行:
改成
记得free~
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <dirent.h>
void printDir(char *dir, int depth) {
DIR *dirp;
struct dirent* dirs;
struct stat* statbuf;
if((dirp = opendir(dir)) == NULL) {
printf( "can not open %s\n", dir);
//exit(0);
return; //不起作用,无限循环打印“can not open”
}
chdir(dir);
while((dirs = readdir(dirp)) != NULL) {
lstat(dirs->d_name, statbuf);
if(S_ISDIR(statbuf->st_mode)) {
// deal with directory except . and ..
if(strcmp(".", dirs->d_name) == 0 ||
strcmp("..", dirs->d_name) == 0) {
//printf("continue...\n");
continue; //只起了一次作用,在第二层目录中又会打印 . 和 ..
}
printf("%*s%s/\n", depth, "", dirs->d_name);
// recurse at a new indent level
printDir(dirs->d_name, depth+4);
} else {
printf("%*s%s\n", depth, "", dirs->d_name);
}
}
chdir("..");
closedir(dirp);
}
int main(int argc, char* argv[]) {
char *topDir = ".";
if(argc >= 2) {
topDir = argv[1];
}
printf("print dir of %s:\n", topDir);
printDir(topDir, 0);
printf("-------------end-------------\n");
exit(0);
}
求解释,分数不多,见谅!
------解决方案--------------------
第11行:
struct stat* statbuf;
改成
struct stat* statbuf = (struct stat*)malloc(sizeof(struct stat));
记得free~