在 Debian(以及其它 Linux 系统)上,使用 C 语言通过 opendir / readdir 获取目录中的文件列表,基本流程如下:
#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
const char *path = argc > 1 ? argv[1] : ".";
DIR *dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
gcc listdir.c -o listdir
./listdir /path/to/dir
opendir(path):打开目录,返回 DIR*readdir(dir):逐个读取目录项entry->d_name:文件名(包含 . 和 ..)closedir(dir):关闭目录. 和 ..if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
#include <sys/stat.h>
struct stat st;
char fullpath[1024];
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
if (stat(fullpath, &st) == 0 && S_ISREG(st.st_mode)) {
printf("file: %s\n", entry->d_name);
}
如果你说的是 shell 命令 而不是 C 的 opendir,在 Debian 上直接用:
ls /path/to/dir
或者递归:
find /path/to/dir
需要我按 C / C++ / shell / Python 哪种方式详细说明吗?