在 Debian(或任何 Linux 系统)中,使用 C 语言 遍历目录,常用的是 opendir() / readdir() 接口。下面给你一个完整、实用的示例,并解释关键点。
opendir() 打开目录readdir() 读取目录项closedir() 关闭目录#include <stdio.h>
#include <dirent.h>
#include <sys/types.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;
}
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
int main() {
DIR *dir;
struct dirent *entry;
struct stat st;
char path[512];
dir = opendir(".");
if (!dir) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
snprintf(path, sizeof(path), "./%s", entry->d_name);
if (stat(path, &st) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(st.st_mode)) {
printf("[DIR] %s\n", entry->d_name);
} else {
printf("[FILE] %s\n", entry->d_name);
}
}
closedir(dir);
return 0;
}
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
void list_dir(const char *path) {
DIR *dir = opendir(path);
struct dirent *entry;
char fullpath[512];
struct stat st;
if (!dir) return;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
if (stat(fullpath, &st) == -1)
continue;
if (S_ISDIR(st.st_mode)) {
printf("[DIR] %s\n", fullpath);
list_dir(fullpath); // 递归
} else {
printf("[FILE] %s\n", fullpath);
}
}
closedir(dir);
}
int main() {
list_dir(".");
return 0;
}
. 和 ... 表示当前目录.. 表示上级目录readdir() 返回的是 struct direntstruct dirent {
ino_t d_ino;
off_t d_off;
unsigned short d_reclen;
unsigned char d_type; // 不一定可靠
char d_name[256];
};
⚠️ d_type 在某些文件系统上不可靠,推荐用 stat()
gcc dir.c -o dir
./dir
| 方法 | 说明 |
|---|---|
opendir/readdir |
最常用、POSIX |
nftw() |
高级目录遍历 |
glob() |
通配符遍历 |
find |
命令行工具 |
如果你需要:
.c)可以直接告诉我,我可以按你的需求写。