gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:56:13 25 4
gpt4 key购买 nike

如何使用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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com