c - 如何使用C中的直接 header 扫描文件夹中的文本

标签 c dirent.h

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

最佳答案

您定义自己的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 页面中进行检查。

如果您还有任何疑问,请随时提问。

关于c - 如何使用C中的直接 header 扫描文件夹中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37236895/

相关文章:

c - Linux 上 C 语言的 Dirent 迭代

c - 在递归函数中使用 readdir 时出现段错误

c - 指针显示为 (null)

c - Windows 中的 UNIX 系统调用 'read' 和 'write'

c - 如何处理文件处理函数的 "*** glibc detected *** ./a: double free or corruption (top): "错误?

c++ - readdir() 显示不可见文件

c - dirent 不使用 unicode

c - 为什么在 C 中打印出变量会改变它们的值?

c - 卸载 Windows 驱动程序

c - 为什么它在 dirent.h 中说 "We must not include limits.h!"?