在 Ubuntu(Linux)下,如果你说的是 用 C/C++ 遍历目录(opendir / readdir),下面给你一个完整、常用的示例。
使用 POSIX 标准目录函数:
opendir():打开目录readdir():读取目录项closedir():关闭目录需要头文件:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
编译运行:
gcc listdir.c -o listdir
./listdir
#include <stdio.h>
#include <dirent.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <dir>\n", argv[0]);
return 1;
}
DIR *dir = opendir(argv[1]);
if (!dir) {
perror("opendir");
return 1;
}
struct dirent *entry;
while ((entry = readdir(dir))) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
void list_dir(const char *path) {
DIR *dir = opendir(path);
if (!dir) return;
struct dirent *entry;
while ((entry = readdir(dir))) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
char full[1024];
snprintf(full, sizeof(full), "%s/%s", path, entry->d_name);
struct stat st;
stat(full, &st);
if (S_ISDIR(st.st_mode)) {
printf("[DIR] %s\n", full);
list_dir(full);
} else {
printf("[FILE] %s\n", full);
}
}
closedir(dir);
}
int main(int argc, char *argv[]) {
const char *path = argc > 1 ? argv[1] : ".";
list_dir(path);
return 0;
}
readdir() 会返回 . 和 ..d_name 中stat()readdir() 不是线程安全的,可用 readdir_r()如果你说的是:
可以告诉我,我可以直接给你对应版本。