【发布时间】:2017-03-04 17:45:55
【问题描述】:
在修改/简化版本的 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' 实用程序类似的输出。关于如何修改我的打印以获得上面列出的“查找”输出的任何帮助。谢谢!
【问题讨论】:
-
无需将
strcasecmp与.一起使用——它的表示不会随大小写而改变。 -
你说得对,我会改的。
-
不清楚你在问什么。
-
无论如何,有两件事 - 最后一个 print 甚至没有添加换行符(它应该,现在它使错误不那么明显了),并检查你正在递归的字符串 (您不应该使用完整路径而不是仅使用最后一个组件进行递归);然后你会注意到你根本不需要
chdir... -
将我递归使用的字符串从最后一个组件更改为完整路径后,我打印了无法打开目录的错误,因为连接的字符串路径不被视为目录的名称。 (即myDir/innerDir不是目录名,应该就是我遍历的innerDir。
标签: c unix directory find-util