在 CentOS(Linux) 下,使用 C 语言 readdir 遍历目录是非常常见的做法。下面给你一个完整、可直接用的示例,并解释关键点。
opendir() 打开目录readdir() 逐个读取目录项closedir() 关闭目录#include <stdio.h>
#include <dirent.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
DIR *dir;
struct dirent *entry;
if (argc < 2) {
printf("用法: %s <目录>\n", argv[0]);
return 1;
}
dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
gcc readdir_test.c -o readdir_test
./readdir_test /etc
. 和 ..while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
printf("%s\n", entry->d_name);
}
#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
void list_dir(const char *path)
{
DIR *dir = opendir(path);
struct dirent *entry;
struct stat st;
if (!dir) return;
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
char fullpath[1024];
snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
if (stat(fullpath, &st) == 0 && S_ISDIR(st.st_mode)) {
printf("[DIR] %s\n", fullpath);
list_dir(fullpath); // 递归
} else {
printf("[FILE] %s\n", fullpath);
}
}
closedir(dir);
}
int main(int argc, char *argv[])
{
if (argc < 2) return 1;
list_dir(argv[1]);
return 0;
}
struct dirent {
ino_t d_ino;
off_t d_off;
unsigned short d_rename;
unsigned char d_type; // 文件类型
char d_name[256];
};
DT_DIR // 目录
DT_REG // 普通文件
DT_LNK // 软链接
readdir 是 线程不安全 的readdir_r(已废弃,不推荐)nftw()scandir()std::filesystem(CentOS 8+)for f in /etc/*; do
echo "$f"
done
如果你是想:
.log)告诉我,我可以直接给你对应方案。