readdir 是一个在 CentOS(以及其他 Unix-like 系统)上用于读取目录内容的函数。它通常与 opendir、closedir 和 dirent.h 库一起使用,以实现对目录的遍历。以下是 readdir 的基本用法示例:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}
与此相比,还有其他方法可以遍历目录,例如使用 find 命令行工具或使用其他编程语言的库函数。以下是一些对比:
find 命令行工具优点:
缺点:
示例:
find /path/to/directory -type f
os 模块优点:
缺点:
示例:
import os
for root, dirs, files in os.walk('/path/to/directory'):
for file in files:
print(os.path.join(root, file))
<filesystem> 库(C++17 及以上)优点:
缺点:
示例:
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
for (const auto &entry : fs::directory_iterator("/path/to/directory")) {
std::cout << entry.path() << std::endl;
}
return 0;
}
readdir:适用于需要在 C/C++ 程序中实现目录遍历的场景,提供了较低级别的控制。find 命令行工具:适用于快速查找文件,不适合复杂的编程逻辑。os 模块:适用于需要在 Python 脚本中实现目录遍历的场景,提供了丰富的功能。<filesystem> 库:适用于需要在 C++ 程序中实现目录遍历的场景,提供了现代 C++ 的语法和功能。选择哪种方法取决于具体的需求、编程语言和环境。