readdir
是一个用于读取目录内容的系统调用,通常与 opendir
、closedir
和 dirent
结构体一起使用。要与其他系统调用结合使用,你需要了解这些系统调用的功能和用法。以下是一个简单的示例,展示了如何使用 opendir
、readdir
、closedir
和 stat
系统调用读取目录内容并获取文件信息:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
struct stat file_stat;
// 打开目录
dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
// 读取目录内容
while ((entry = readdir(dir)) != NULL) {
// 跳过当前目录(.)和上级目录(..)
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 获取文件信息
char file_path[1024];
snprintf(file_path, sizeof(file_path), "%s/%s", argv[1], entry->d_name);
if (stat(file_path, &file_stat) == -1) {
perror("stat");
closedir(dir);
return EXIT_FAILURE;
}
// 输出文件名和文件类型
printf("%s: ", entry->d_name);
if (S_ISREG(file_stat.st_mode)) {
printf("Regular file\n");
} else if (S_ISDIR(file_stat.st_mode)) {
printf("Directory\n");
} else {
printf("Other\n");
}
}
// 关闭目录
closedir(dir);
return EXIT_SUCCESS;
}
这个示例程序接受一个目录路径作为命令行参数,然后使用 opendir
打开目录。接着,它使用 readdir
读取目录中的每个条目,并使用 stat
获取每个条目的文件信息。最后,它关闭目录并退出。
你可以根据需要修改此示例,以便与其他系统调用结合使用。例如,你可以使用 open
、read
和 close
系统调用来读取文件内容,或者使用 access
系统调用来检查文件的访问权限。