在CentOS中,你可以使用readdir
函数来实现目录监控。readdir
函数是C语言库函数,用于读取目录流中的条目。以下是一个简单的示例,展示了如何使用readdir
函数来监控一个目录:
monitor_directory.c
的C文件,并添加以下代码:#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
void monitor_directory(const char *path) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
dir = opendir(path);
if (dir == NULL) {
perror("opendir");
return;
}
while ((entry = readdir(dir)) != NULL) {
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
if (stat(full_path, &statbuf) == -1) {
perror("stat");
continue;
}
printf("Entry: %s\n", entry->d_name);
printf("Path: %s\n", full_path);
printf("Size: %ld\n", statbuf.st_size);
printf("Last modified: %s", ctime(&statbuf.st_mtime));
}
closedir(dir);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory_path>\n", argv[0]);
return 1;
}
monitor_directory(argv[1]);
return 0;
}
gcc
编译器编译此代码:gcc -o monitor_directory monitor_directory.c
./monitor_directory /path/to/your/directory
这个程序将输出指定目录中的所有文件和子目录的名称、路径、大小和最后修改时间。你可以根据需要修改此程序,以实现更复杂的目录监控功能。
请注意,这个示例仅适用于实时监控目录的一次性操作。如果你需要持续监控目录的变化(例如,新文件被添加或现有文件被修改),你可能需要使用其他方法,例如inotify
。