c - 如何使用C语言找到目录中具有相同扩展名的所有文件?

标签 c

如何使用C语言找到目录中具有相同扩展名的所有文件? 我的意思是我只想输入扩展名作为参数,然后我想列出我输入的扩展名的所有文件

int main (int argc,char *argv[]) 
{
    DIR *dir;
    struct dirent *dent;

    if (argc != 3) {
        printf("usage: ./Exe_Name dir_name file_name");    
    }
    dir = opendir(argv[1]);
    //this part 
    if(dir!=NULL) { 
        while((dent=readdir(dir))!=NULL)
           if(strcmp(dent->d_name,argv[2])==0)
               printf("%s\n",dent->d_name);

    } else
        printf ("Cannot open directory '%s'\n", argv[1]);
    closedir(dir);
    return 0; 
}

最佳答案

您想要使用scandir。来自 man page :

   int scandir(const char *dir, struct dirent ***namelist,
          int(*filter)(const struct dirent *),
          int(*compar)(const struct dirent **, const struct dirent **));

   int alphasort(const void *a, const void *b);
   int versionsort(const void *a, const void *b);

The scandir() function scans the directory dir, calling filter() on each directory entry. Entries for which filter() returns non-zero are stored in strings allocated via malloc(), sorted using qsort() with the comparison function compar(), and collected in array namelist which is allocated via malloc(). If filter is NULL, all entries are selected.

The alphasort() and versionsort() functions can be used as the comparison function compar(). The former sorts directory entries using strcoll(3), the latter using strverscmp(3) on the strings (*a)->d_name and (*b)->d_name.

关于c - 如何使用C语言找到目录中具有相同扩展名的所有文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36500446/

相关文章:

c - c中按字母顺序排列的第一个和最后一个单词

c - 二维数组打印错误

c++ - unsigned char* 值转为十六进制

c - Visual C 链接器在 32 位和 64 位上的行为不同

c - 如何将一个指针指向的地址分配给另一个本地指针

c - #如果已定义 (x) || (y) ;这是有效的吗?

c - 如何使用 accelstepper arduino 库移动指定数量的步数,检查外部输入,然后继续?

c - 将线段延伸特定距离

c - C 中的匹配哈希值

C++ 到 C 的区别 & *