c语言如何获得文件夹下的所有文件名
在C语言中,可使用dirent.h头文件中的DIR和dirent结构体和readdir函数来获得文件夹下的所有文件名。下面是一个简单的示例代码:
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *ent;
// 打开文件夹
dir = opendir("folder_path");
if (dir == NULL) {
printf("没法打开文件夹
");
return 1;
}
// 读取文件夹中的文件
while ((ent = readdir(dir)) != NULL) {
// 过滤掉当前文件夹(.)和上级文件夹(..)的记录
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) {
continue;
}
printf("%s
", ent->d_name);
}
// 关闭文件夹
closedir(dir);
return 0;
}
在代码中,folder_path需要替换为实际文件夹的路径。opendir函数用于打开文件夹,返回一个指向DIR类型的指针。readdir函数用于读取文件夹中的文件,返回一个指向dirent结构体的指针,其中包括文件名等信息。通过循环遍历使用readdir函数获得的文件信息,可以获得到文件夹下的所有文件名。最后,使用closedir函数关闭文件夹。
TOP