2016-05-15 69 views
-2

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

+1

想法是在目录路径上使用'opendir',然后用'readdir'循环查找所有文件,并且对于每个文件,您可能还必须“打开”,“读取”和“关闭”。你也可以为每个文件使用'fopen','fread'和'fclose'。一旦完成,你还应该调用'closedir'。 –

+0

在向全世界寻求帮助之前,请自己做一些研究。谢谢。 – alk

+0

谢谢Henrik!并猜测我尝试了什么,烷。并失败。那么“向世界求助”有什么不对?这是一个问题和答案的网站! –

回答

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()功能,它也许更容易这样,但我想告诉你这种方法,因为它是非常ilustrating。但是最简单的遍历低谷文件夹/文件层次结构的方法是NFTW函数。确保你在man页面检查。

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

+0

非常感谢你Aleksandar !!! –