在 Ubuntu(Linux)下使用 C 语言的 readdir 来读取目录,一般步骤如下:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir("."); // 打开当前目录
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
opendirDIR *opendir(const char *name);
DIR*,失败返回 NULLreaddirstruct dirent *readdir(DIR *dirp);
NULL 表示读取结束或出错struct direntstruct dirent {
ino_t d_ino;
off_t d_off;
unsigned short d_reclen;
unsigned char d_type;
char d_name[256];
};
常用字段:
d_name:文件名d_type:文件类型(可选)closedirint closedir(DIR *dirp);
. 和 ..while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
printf("%s\n", entry->d_name);
}
gcc readdir_example.c -o readdir_example
./readdir_example
closedirPermission denied)如果你需要 递归遍历目录、区分文件/目录 或 使用 readdir_r(线程安全),我也可以继续讲。