readdir 函数是用于读取目录内容的 POSIX 标准函数。在 Debian 或其他基于 Linux 的系统上,你可以使用这个函数来遍历目录中的文件和子目录。下面是一些使用 readdir 函数的基本技巧和示例:
基本用法
-
包含头文件:
使用readdir函数之前,确保包含了必要的头文件:#include <dirent.h> #include <stdio.h> #include <stdlib.h> -
打开目录:
使用opendir函数打开一个目录,并返回一个DIR指针。DIR *dir = opendir("."); if (dir == NULL) { perror("opendir"); exit(EXIT_FAILURE); } -
读取目录项:
使用readdir函数读取目录中的每一项。struct dirent *entry; while ((entry = readdir(dir)) != NULL) { printf("%s\n", entry->d_name); } -
关闭目录:
使用closedir函数关闭目录。closedir(dir);
示例代码
下面是一个完整的示例程序,演示如何使用 readdir 函数列出当前目录下的所有文件和子目录:
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
DIR *dir;
struct dirent *entry;
// 打开当前目录
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
// 遍历目录中的每一项
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
// 关闭目录
closedir(dir);
return EXIT_SUCCESS;
}
高级用法
-
过滤特定文件类型:
你可以根据需要过滤特定类型的文件。例如,只列出.txt文件:while ((entry = readdir(dir)) != NULL) { if (strstr(entry->d_name, ".txt") != NULL) { printf("%s\n", entry->d_name); } } -
获取文件的详细信息:
结合stat函数可以获取文件的详细信息,如文件大小、修改时间等。struct stat file_stat; char path[1024]; while ((entry = readdir(dir)) != NULL) { snprintf(path, sizeof(path), "./%s", entry->d_name); if (stat(path, &file_stat) == 0) { printf("%s - %ld bytes\n", entry->d_name, file_stat.st_size); } } -
递归遍历目录:
如果你需要递归遍历目录及其子目录,可以编写一个递归函数。void list_directory(const char *path) { DIR *dir; struct dirent *entry; char full_path[1024]; dir = opendir(path); if (dir == NULL) { perror("opendir"); return; } while ((entry = readdir(dir)) != NULL) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name); if (entry->d_type == DT_DIR) { list_directory(full_path); } else { printf("%s\n", full_path); } } closedir(dir); } int main() { list_directory("."); return EXIT_SUCCESS; }
通过这些技巧和示例,你应该能够在 Debian 系统上有效地使用 readdir 函数来处理目录和文件。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1474930.html