需求描述
在Linux中使用C语言开发时,有时候需要获取指定目录中的文件和文件夹,当然,可以使用“exec"执行"ls"命令,取得命令的输出结果来获取,但解析结果还是挺麻烦了,使用POSIX的兼容的API dirent.h中的函数来获取就可以了。
示例代码
以下是在linux中使用POSIX兼容的API,opendir、readdir获取指定目录中的所有文件和文件夹的示例代码。
/*
* This program displays the names of all files in the current directory.
*/
#include <dirent.h>
#include <stdio.h>
int main(void) {
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d) {
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(d);
}
return(0);
}
评论区