在Linux系統中,readdir
函數通常用于讀取目錄的內容。然而,如果你想要實現文件監控,即實時檢測目錄中文件的變化(如新增、刪除或修改),readdir
本身并不直接提供這樣的功能。你需要結合其他機制來實現這一目標。
以下是一些常用的方法來監控Linux目錄中的文件變化:
inotify
inotify
是Linux內核提供的一種文件系統事件監控機制。你可以使用 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];
// 創建inotify實例
fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
return 1;
}
// 添加監控目錄
wd = inotify_add_watch(fd, "/path/to/directory", IN_MODIFY | IN_CREATE | IN_DELETE);
if (wd < 0) {
perror("inotify_add_watch");
return 1;
}
// 讀取事件
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 created\n", event->name);
} else if (event->mask & IN_DELETE) {
printf("File %s deleted\n", event->name);
} else if (event->mask & IN_MODIFY) {
printf("File %s modified\n", event->name);
}
}
i += EVENT_SIZE + event->len;
}
i = 0;
}
// 移除監控
inotify_rm_watch(fd, wd);
close(fd);
return 0;
}
fswatch
fswatch
是一個第三方工具,可以監控文件系統事件并執行命令。
fswatch
:sudo apt-get install fswatch # Debian/Ubuntu
sudo yum install fswatch # CentOS/RHEL
fswatch -o /path/to/directory | while read path; do
echo "File $path changed"
done
inotifywait
inotifywait
是 inotify-tools
包中的一個工具,可以等待并打印文件系統事件。
inotify-tools
:sudo apt-get install inotify-tools # Debian/Ubuntu
sudo yum install inotify-tools # CentOS/RHEL
inotifywait -m -r -e create,delete,modify /path/to/directory
ls
和 diff
你可以定期運行 ls
命令并比較結果來檢測文件變化。
#!/bin/bash
DIR="/path/to/directory"
PREV_FILE_LIST=$(ls $DIR)
while true; do
CURRENT_FILE_LIST=$(ls $DIR)
DIFF=$(diff <(echo "$PREV_FILE_LIST") <(echo "$CURRENT_FILE_LIST"))
if [ -n "$DIFF" ]; then
echo "Files have changed:"
echo "$DIFF"
PREV_FILE_LIST=$CURRENT_FILE_LIST
fi
sleep 1
done
inotify
是最直接和高效的方法,適用于需要實時監控的場景。fswatch
和 inotifywait
是第三方工具,使用簡單,適合快速實現監控功能。ls
和 diff
的方法雖然簡單,但效率較低,適用于文件變化不頻繁的場景。選擇哪種方法取決于你的具體需求和環境。