2015-12-03 32 views
-1

我试图在执行我的程序时在用户在命令行上指定的目录中搜索文件。它应该查看指定的目录,并检查该目录内的子目录并递归搜索该文件。在目录中搜索以查看C中是否存在文件

我在这里有打印语句,试图分析变量传递的方式以及它们如何变化。在我的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]); 

} 
+1

你调用'chdir()'的返回值是多少?如果失败,您的代码将无法工作。你还需要检查'lstat()'的返回值。 –

+0

@AndrewHenle好主意。我加了两个检查。 chdir()似乎没有错误。直到大约一半时,lstat()才会出错。它通过两个子目录循环,然后失败并将程序的其余部分拧紧。 – Ryan

+1

你的逻辑错误。你'chdir'进入目录,但永远不会恢复。第一个目录后的所有内容都将失败。 –

回答

0

有这样一棵树行走的POSIX函数。它叫做nftw()

它提供了回调机制,它还检测由构造严重的符号链接链引起的链接。

所以我建议你使用它,而不是你这样做。

像往常一样man nftw将详细解释它的操作。标准的Linux/Unix包含文件是ftw.h.

注意它们是一个称为ftw()的函数,现在显然已经过时了。

0

正如Andrew Medico指出的那样:chdir下降到目录但从不回去。因此,只需要插入

chdir(".."); // change back to upper directory 

while循环的结束和traverse()功能的端部之间。

相关问题