使用经过修改/更简单的Unix版本'找到'实用程序,当我打印文件时,我的格式是关闭的。
运行:
./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'树相似的输出。效用。任何有关如何修改我的打印以获得'找到'输出我在上面列出。谢谢!
答案 0 :(得分:0)
在递归调用时只是一个错误的参数,发送完整路径:
printdir(path, depth + 1);
然后对于非目录条目,还打印完整路径:
printf("%s/%s\n", dir, entry->d_name);
---- ---- EDIT
在生成完整路径时删除对chdir
的所有调用。
---- EDIT-2 ----
lstat
没有调用正确的路径,修改为:
while((entry = readdir(dp)) != NULL) {
path = malloc(strlen(dir) + strlen(entry->d_name) + 2);
strcpy(path, dir);
strcat(path, "/");
strcat(path, entry->d_name);
lstat(path, & statbuf);