在 Linux 下,opendir
函数用于打开一个目录流,以便你可以使用 readdir
函数读取目录中的条目。然而,opendir
本身并不提供直接的目录监控功能。要实现目录监控,你可以结合使用 inotify
API 或轮询目录变化的方法。
下面是一个简单的示例,展示如何使用 opendir
和 readdir
来遍历目录,并结合 inotify
来监控目录变化:
opendir
和 readdir
遍历目录#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/inotify.h>
#include <unistd.h>
#define EVENT_SIZE ( sizeof (struct inotify_event) )
#define BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) )
void list_directory(const char *path) {
DIR *dir;
struct dirent *entry;
dir = opendir(path);
if (!dir) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
list_directory(argv[1]);
// Initialize inotify
int fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
return EXIT_FAILURE;
}
// Add watch for the directory
int wd = inotify_add_watch(fd, argv[1], IN_MODIFY | IN_CREATE | IN_DELETE);
if (wd < 0) {
perror("inotify_add_watch");
close(fd);
return EXIT_FAILURE;
}
// Read events from inotify
char buffer[BUF_LEN];
while (1) {
ssize_t length = read(fd, buffer, BUF_LEN);
if (length < 0) {
perror("read");
break;
}
int i = 0;
while (i < length) {
struct inotify_event *event = (struct inotify_event *) &buffer[i];
if (event->len) {
if (event->mask & IN_MODIFY) {
printf("File modified: %s\n", event->name);
}
if (event->mask & IN_CREATE) {
printf("File created: %s\n", event->name);
}
if (event->mask & IN_DELETE) {
printf("File deleted: %s\n", event->name);
}
}
i += EVENT_SIZE + event->len;
}
}
// Remove watch and close inotify
inotify_rm_watch(fd, wd);
close(fd);
return EXIT_SUCCESS;
}
遍历目录:
opendir
打开目录。readdir
读取目录中的条目并打印。监控目录变化:
inotify_init
初始化 inotify
。inotify_add_watch
添加对指定目录的监控,监控事件包括文件修改、创建和删除。read
读取 inotify
事件,并根据事件类型打印相应的消息。inotify_rm_watch
移除监控并关闭 inotify
。gcc -o monitor_directory monitor_directory.c
./monitor_directory /path/to/directory
这个示例程序会遍历指定目录中的所有文件,并持续监控该目录的变化,当有文件被修改、创建或删除时,会打印相应的消息。