readdir 是一個用于讀取目錄內容的函數,通常在 C/C++ 語言中使用。要利用 readdir 實現文件監控和日志記錄,你需要定期檢查目錄內容的變化,并將變化記錄到日志文件中。以下是一個簡單的示例:
首先,確保你的系統上安裝了必要的開發工具和庫。
創建一個名為 file_monitor.c 的 C 文件,并添加以下代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#define LOG_FILE "file_monitor.log"
void log_message(const char *message) {
FILE *log_file = fopen(LOG_FILE, "a");
if (log_file == NULL) {
perror("Failed to open log file");
return;
}
time_t now = time(NULL);
fprintf(log_file, "%s: %s\n", ctime(&now), message);
fclose(log_file);
}
void monitor_directory(const char *path) {
DIR *dir = opendir(path);
if (dir == NULL) {
perror("Failed to open directory");
return;
}
struct dirent *entry;
struct stat statbuf;
char last_statbuf[PATH_MAX];
while ((entry = readdir(dir)) != NULL) {
snprintf(last_statbuf, sizeof(last_statbuf), "%s/%s", path, entry->d_name);
if (stat(last_statbuf, &statbuf) == -1) {
perror("Failed to get file status");
continue;
}
// Check if the file is new or has been modified
if (entry->d_type == DT_REG) {
FILE *last_stat_file = fopen(last_statbuf, "r");
if (last_stat_file == NULL) {
log_message(entry->d_name);
fclose(last_stat_file);
continue;
}
int new_file = fscanf(last_stat_file, "%ld", &statbuf.st_mtime) != 1;
fclose(last_stat_file);
if (new_file || statbuf.st_mtime != *(long *)last_statbuf) {
log_message(entry->d_name);
}
}
}
closedir(dir);
}
int main() {
const char *path = ".";
while (1) {
monitor_directory(path);
sleep(60); // Check the directory every 60 seconds
}
return 0;
}
gcc file_monitor.c -o file_monitor
./file_monitor
這個程序將每 60 秒檢查一次當前目錄(.)的內容,并將新文件或已修改的文件記錄到 file_monitor.log 文件中。你可以根據需要調整檢查間隔和監控目錄。
請注意,這個示例僅適用于簡單的文件監控場景。在實際應用中,你可能需要處理更多的邊緣情況,例如符號鏈接、權限問題等。此外,對于更高級的文件監控需求,你可以考慮使用專門的庫,如 inotify(Linux)或 ReadDirectoryChangesW(Windows)。