查找文件算法

查找文件算法

我使用的是 Linux(Ubuntu 12.04)。我想知道“查找”命令是如何工作的。我的问题是,如何运行和测试从 GNU findutils 下载的“find”C 文件?

答案1

treatDirectory(dir) {
  open directory dir
  for each entry in dir
    if the entry is a match
      print it
    if the entry is a directory
      call treatDirectory(entry)
}

call treatDirectory(dir) for each directory given as parameter.

答案2

更多关于 StackOverflow 的问题,但我已经找到了这段代码。

为了找到正确的方法来解决这个问题,分析源代码find将产生更正确的教训。你实际上不必让它运行来弄清楚它在做什么,你可以阅读每一行并谷歌搜索你不明白的内容。但使用调试器单步调试可能会有所帮助。如果您在编译时遇到问题,请将其带到 SO 或您拥有的任何其他资源来帮助您构建环境。

#include <dirent.h>

int doSomethingWithTheFileSystem()
{
  DIR *directory;
  struct dirent *whatDoesEPstandfor; //seriously, you terse C bastards just HATE new guys don't you?
  int count = 0;
  char filename[50]; //This is going to bite you in the ass when you have a filename larger than 50. Seriously, don't do this. 
  FILE* file;

  directory = opendir ("."); 
  if(directory != NULL)
  {
    while((whatDoesEPstandfor = readdir(directory)) != NULL )
    {
      printf("Looking at: %s\n",whatDoesEPstandfor->d_name );
      if(strstr(whatDoesEPstandfor->d_name,"thatThingYouAreLookingFor") != NULL)
      {
        printf("Found it at: %s\n",whatDoesEPstandfor->d_name);
      }
    }
    closedir (directory);
  }
}

相关内容