【发布时间】:2016-03-07 12:05:39
【问题描述】:
我正在尝试在执行我的程序时在命令行上由用户指定的目录中搜索文件。它应该查看指定的目录,并检查该目录中的子目录并递归搜索该文件。
我在这里有打印语句,试图分析正在传递的变量以及它们是如何变化的。在我的 while 循环中,它永远不会检查它是否是一个文件,或者只是 else 语句说它没有找到。每次检查是否是目录都是真的,显然不是这样。
感谢您的帮助。我对 dirent 和 stat 不是很熟悉/不习惯,所以我一直在尝试检查并确保我在此期间正确使用它们。
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <errno.h>
void traverse(char *dir, char *file) {
DIR *directory;
struct dirent *structure;
struct stat info;
printf("Current directory to search through is: %s\n", dir);
printf("Current file to search for is: %s\n", file);
printf("\n");
printf("\n");
// make sure the directory can be opened
if((directory = opendir(dir)) == NULL) {
fprintf(stderr, "The directory could not be opened. %s\n", strerror(errno));
return;
}
chdir(dir); // change to the directory
while((structure = readdir(directory)) != NULL) { // loop through it
fprintf(stderr, "before the change it is: %s\n", dir);
lstat(structure->d_name, &info); // get the name of the next item
if(S_ISDIR(info.st_mode)) { // is it a directory?
printf("checking if it's a directory\n");
if(strcmp(".", structure->d_name) == 0 ||
strcmp("..", structure->d_name) == 0)
continue; // ignore the . and .. directories
dir = structure->d_name;
fprintf(stderr, "after the change it is: %s\n", dir);
printf("About to recurse...\n");
printf("\n");
traverse(structure->d_name, file); // recursively traverse through that directory as well
}
else if(S_ISREG(info.st_mode)) { // is it a file?
printf("checking if it's a file\n");
if(strcmp(file, structure->d_name) == 0) { // is it what they're searching for?
printf("The file was found.\n");
}
}
else {
printf("The file was nout found.\n");
}
}
closedir(directory);
}
int main(int argc, char *argv[]) {
// make sure they entered enough arguments
if (argc < 3) {
fprintf(stderr, "You didn't enter enough arguments on the command line!\n");
return 3;
}
traverse(argv[2], argv[1]);
}
【问题讨论】:
-
调用
chdir()的返回值是多少?如果失败,您的代码将无法工作。您还需要检查来自lstat()的返回值。 -
@AndrewHenle 好主意。我添加了两者的检查。 chdir() 似乎永远不会出错。 lstat() 直到大约一半时才会出错。它遍历两个子目录,然后失败并搞砸了程序的其余部分。
-
你的逻辑错了。您
chdir进入目录但永远不会返回。第一个目录之后的所有内容都会失败。