readdir
是一个用于读取目录内容的函数,通常在 C/C++ 语言中使用。要利用 readdir
实现文件监控,你需要定期调用该函数并检查目录内容的变化。以下是一个简单的示例,展示了如何使用 readdir
实现文件监控:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#define CHECK_INTERVAL 1 // 检查间隔时间(秒)
int main() {
const char *path = "/path/to/your/directory"; // 要监控的目录路径
DIR *dir;
struct dirent *entry;
struct stat file_stat;
char last_files[1024][256]; // 存储上一次检查时的文件名
int file_count = 0;
if (!(dir = opendir(path))) {
perror("opendir");
exit(EXIT_FAILURE);
}
// 初始化 last_files 数组
while ((entry = readdir(dir)) != NULL) {
if (stat(path "/" entry->d_name, &file_stat) == 0) {
if (S_ISREG(file_stat.st_mode)) {
strcpy(last_files[file_count++], entry->d_name);
}
}
}
closedir(dir);
while (1) {
sleep(CHECK_INTERVAL);
if (!(dir = opendir(path))) {
perror("opendir");
exit(EXIT_FAILURE);
}
int current_file_count = 0;
while ((entry = readdir(dir)) != NULL) {
if (stat(path "/" entry->d_name, &file_stat) == 0) {
if (S_ISREG(file_stat.st_mode)) {
int file_found = 0;
for (int i = 0; i < file_count; i++) {
if (strcmp(last_files[i], entry->d_name) == 0) {
file_found = 1;
break;
}
}
if (!file_found) {
printf("New file detected: %s\n", entry->d_name);
}
}
}
}
// 更新 last_files 数组
for (int i = 0; i < file_count; i++) {
if (stat(path "/" last_files[i], &file_stat) != 0) {
printf("File removed: %s\n", last_files[i]);
}
}
for (int i = 0; i < file_count && current_file_count < file_count; i++) {
if (strcmp(last_files[i], entry->d_name) != 0) {
printf("File changed: %s\n", last_files[i]);
}
}
if (current_file_count < file_count) {
printf("New file detected: %s\n", entry->d_name);
}
closedir(dir);
// 更新 last_files 数组
for (int i = 0; i < file_count; i++) {
strcpy(last_files[i], entry->d_name);
}
file_count = current_file_count;
}
return 0;
}
这个示例程序会定期检查指定目录的内容,并报告新文件、删除的文件和更改的文件。请注意,这个示例仅适用于简单的文件监控任务,可能无法检测到所有类型的文件更改(例如,重命名文件)。对于更高级的文件监控需求,可以考虑使用 inotify
(Linux)或其他操作系统提供的文件监控机制。