使用 Unix 'find' 实用程序的修改/更简单版本,当我打印出文件时,我的格式已关闭。
跑步:
./a.out mydir -print
输出应该类似于 find,如下:
mydir
mydir/innerDir
mydir/innerDir/innerFile
mydir/testFile
但是,我的输出如下:
mydir/innerDir
innerFile/testFile
这是我拥有的遍历目录内容的函数:
void printdir(char *dir, int depth) {
DIR *dp;
struct dirent *entry;
struct stat statbuf;
int spaces = depth * 4;
char *path;
if((dp = opendir(dir)) == NULL) {
fprintf(stderr, "Error! Unable to open: %s\n", dir);
exit(EXIT_FAILURE);
}
chdir(dir);
while((entry = readdir(dp)) != NULL) {
lstat(entry->d_name, & statbuf);
if(S_ISDIR(statbuf.st_mode)) {
if(strcasecmp(".", entry->d_name) == 0 ||
strcasecmp("..", entry->d_name) == 0)
continue;
path = malloc(strlen(dir) + strlen(entry->d_name) + 2);
strcpy(path, dir);
strcat(path, "/");
strcat(path, entry->d_name);
// printf("%*s|-- %s/\n", spaces, "", entry->d_name);
printf("%s\n", path);
printdir(entry->d_name, depth + 1);
}
else
// printf("%*s|-- %s\n", spaces, "", entry->d_name);
printf("%s/", entry->d_name);
}
chdir("..");
closedir(dp);
}
上面注释的行打印出与 Unix 'tree' 实用程序类似的输出。关于如何修改我的打印以获得上面列出的“查找”输出的任何帮助。谢谢!