【问题标题】:C get all files with certain extensionC 获取具有特定扩展名的所有文件
【发布时间】:2014-04-05 20:20:14
【问题描述】:

如何在带有“.ngl”扩展名的目录中查找所有扩展名?

【问题讨论】:

  • 什么操作系统?还是您需要跨平台解决方案?
  • 查看 opendir readdir 和 glob

标签: c file


【解决方案1】:

C 没有标准化的目录管理,即 POSIX(或 Windows,如果您愿意的话)。
在 POSIX 中,您可以执行以下操作:

  1. 获取包含目录路径的char *
  2. 在上面使用opendir(),你会得到一个DIR *
  3. DIR * 上反复使用readdir() 会为您提供目录中的struct dirent* 条目
  4. stuct dirent* 包含文件的名称,包括扩展名 (.ngl)。它还包含有关条目是常规文件还是其他内容(符号链接、子目录等)的信息

【讨论】:

    【解决方案2】:

    如果你想通过一个系统调用获取文件夹中具有相同扩展名的文件名列表,你可以尝试使用scandir,而不是使用opendirreaddir。唯一要记住的是,您需要释放由scandir 分配的内存。

       /* print files in current directory with specific file extension */
       #include <string.h>
       #include <stdio.h>
       #include <stdlib.h>
       #include <dirent.h>
    
       /* when return 1, scandir will put this dirent to the list */
       static int parse_ext(const struct dirent *dir)
       {
         if(!dir)
           return 0;
    
         if(dir->d_type == DT_REG) { /* only deal with regular file */
             const char *ext = strrchr(dir->d_name,'.');
             if((!ext) || (ext == dir->d_name))
               return 0;
             else {
               if(strcmp(ext, ".ngl") == 0)
                 return 1;
             }
         }
    
         return 0;
       }
    
       int main(void)
       {
           struct dirent **namelist;
           int n;
    
           n = scandir(".", &namelist, parse_ext, alphasort);
           if (n < 0) {
               perror("scandir");
               return 1;
           }
           else {
               while (n--) {
                   printf("%s\n", namelist[n]->d_name);
                   free(namelist[n]);
               }
               free(namelist);
           }
    
           return 0;
       }
    

    【讨论】:

    • 为什么必须free() 内存是一个缺点?这就是整天必须做的事情......
    • 我想说的是,有时程序员忘记释放内存或不知道他/她应该释放内存,因为它是由scandir而不是程序员自己分配的。跨度>
    • 没错,但适用于各种内存分配。也许措辞可以是“唯一要考虑的事情”或“要记住”......
    猜你喜欢
    • 2019-06-14
    • 2011-09-25
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 2010-12-03
    • 2023-03-02
    • 2021-06-08
    相关资源
    最近更新 更多