-2

我需要找到一种方法来扫描文件夹(例如 -C:\Users\User\Documents\HW)并检查我是否从用户那里获得了一些文本。我需要返回哪些文件具有完全相同的文本。我以前从未使用过 dirent.h,也不知道如何使用它;

4

1 回答 1

0

您定义自己的error处理错误的函数:

// Standard error function
void fatal_error(const char* message) {

  perror(message);
  exit(1);
}

遍历功能基本上是统计当前文件,如果该文件是目录,我们将进入该目录。在目录本身非常重要的是检查当前目录是否为 . 或 .. 因为这会导致不定式循环。

void traverse(const char *pathName){

  /* Fetching file info */
  struct stat buffer;
  if(stat(pathName, &buffer) == -1)
    fatalError("Stat error\n");

  /* Check if current file is regular, if it is regular, this is where you 
     will see if your files are identical. Figure out way to do this! I'm 
     leaving this part for you. 
  */

  /* However, If it is directory */
  if((buffer.st_mode & S_IFMT) == S_IFDIR){

    /* We are opening directory */
    DIR *directory = opendir(pathName);
    if(directory == NULL)
      fatalError("Opening directory error\n");

    /* Reading every entry from directory */
    struct dirent *entry;
    char *newPath = NULL;
    while((entry = readdir(directory)) != NULL){

      /* If file name is not . or .. */
      if(strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")){

        /* Reallocating space for new path */
        char *tmp = realloc(newPath, strlen(pathName) + strlen(entry->d_name) + 2);
        if(tmp == NULL)
          fatalError("Realloc error\n");
        newPath = tmp;

        /* Creating new path as: old_path/file_name */
        strcpy(newPath, pathName);
        strcat(newPath, "/");
        strcat(newPath, entry->d_name);

        /* Recursive function call */
        traverse(newPath);
      }
    }
    /* Since we always reallocate space, this is one memory location, so we free that memory*/
    free(newPath);

    if(closedir(directory) == -1)
      fatalError("Closing directory error\n");
  }

}

您也可以使用chdir()函数来执行此操作,这样可能更容易,但我想以这种方式向您展示,因为它非常具有说明性。但是遍历文件夹/文件层次结构的最简单方法是NFTW函数。确保在man页面中检查。

如果您还有其他问题,请随时提问。

于 2016-05-15T10:19:42.153 回答