在Linux系统中,readdir
函数通常与opendir
、closedir
和dirent
结构体一起使用,用于读取目录的内容。然而,readdir
本身并不提供目录监控的功能。如果你想要监控一个目录的变化(例如,文件或子目录的添加、删除或修改),你需要使用其他机制,比如inotify
。
以下是使用readdir
读取目录内容的基本示例:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.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;
}
如果你想要监控目录的变化,可以使用inotify
API。以下是一个简单的例子,展示了如何使用inotify
来监控一个目录:
#include <stdio.h>
#include <stdlib.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 ) )
int main(int argc, char **argv) {
int length, i = 0;
int fd;
int wd;
char buffer[BUF_LEN];
// 检查参数
if (argc != 2) {
printf("Usage: %s <directory_to_watch>\n", argv[0]);
return 1;
}
// 创建inotify实例
fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
return 1;
}
// 添加要监控的目录
wd = inotify_add_watch(fd, argv[1], IN_MODIFY | IN_CREATE | IN_DELETE);
if (wd < 0) {
perror("inotify_add_watch");
return 1;
}
// 读取inotify事件
while (1) {
length = read(fd, buffer, BUF_LEN);
if (length < 0) {
perror("read");
return 1;
}
while (i < length) {
struct inotify_event *event = (struct inotify_event *) &buffer[i];
if (event->len) {
if (event->mask & IN_CREATE) {
printf("File %s was created.\n", event->name);
} else if (event->mask & IN_DELETE) {
printf("File %s was deleted.\n", event->name);
} else if (event->mask & IN_MODIFY) {
printf("File %s was modified.\n", event->name);
}
}
i += EVENT_SIZE + event->len;
}
i = 0;
}
// 移除监控并关闭inotify实例
(void) inotify_rm_watch(fd, wd);
(void) close(fd);
return 0;
}
在这个例子中,我们创建了一个inotify
实例,并添加了对指定目录的监控。我们监控了三种事件:文件的修改(IN_MODIFY
)、文件的创建(IN_CREATE
)和文件的删除(IN_DELETE
)。当这些事件发生时,程序会打印出相应的消息。
要编译这个程序,你需要链接inotify
库:
gcc -o inotify_example inotify_example.c
然后运行程序,并指定你想要监控的目录:
./inotify_example /path/to/directory
请注意,这个例子是一个简单的演示,实际应用中可能需要更复杂的错误处理和逻辑。此外,inotify
有其限制,比如监控的文件描述符数量和事件队列的大小,这些可能需要根据你的具体需求进行调整。