#include <unistd.h>
#include <linux/inotify.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#define MAX_PATH 1024
void copy_file(char *src,char *dest);
char * monitored_files[] = {
"/home/xiaohei/Desktop/abc/"
};
struct wd_name {
int wd;
char * name;
};
#define WD_NUM 1
struct wd_name wd_array[WD_NUM];
char * event_array[] = {
"File was accessed",
"File was modified",
"File attributes were changed",
"writtable file closed",
"Unwrittable file closed",
"File was opened",
"File was moved from X",
"File was moved to Y",
"Subfile was created",
"Subfile was deleted",
"Self was deleted",
"Self was moved",
"",
"Backing fs was unmounted",
"Event queued overflowed",
"File was ignored"
};
#define EVENT_NUM 16
#define MAX_BUF_SIZE 1024
int main(void)
{
int fd;
int wd;
char buffer[1024];
char * offset = NULL;
struct inotify_event * event;
int len, tmp_len;
char strbuf[16];
int i = 0;
char name[50]={0},srcname[50]={0},destname[50]={0};
fd = inotify_init();
if (fd < 0) {
printf("Fail to initialize inotify.\n");
exit(-1);
}
for (i=0; i<WD_NUM; i++) {
wd_array[i].name = monitored_files[i];
wd = inotify_add_watch(fd, wd_array[i].name,IN_ALL_EVENTS);
if (wd < 0) {
printf("Can't add watch for %s.\n", wd_array[i].name);
exit(-1);
}
wd_array[i].wd = wd;
}
while(len = read(fd, buffer, MAX_BUF_SIZE)) {
offset = buffer;
printf("Some event happens, len = %d.\n", len);
event = (struct inotify_event *)buffer;
strcpy(name,event->name);
while (((char *)event - buffer) < len) {
if (event->mask & IN_ISDIR) {
memcpy(strbuf, "Direcotory", 11);
}
else {
memcpy(strbuf, "File", 5);
}
printf("Object type: %s\n", strbuf);
for (i=0; i<WD_NUM; i++) {
if (event->wd != wd_array[i].wd) continue;
printf("Object name: %s\n", wd_array[i].name);
strcpy(srcname,wd_array[i].name);
strcpy(destname,"/home/xiaohei/Desktop/123/");
strcat(srcname,name);
strcat(destname,name);
printf("*************%s\n",srcname);
printf("*************%s\n",destname);
break;
}
printf("Event mask: %08X\n", event->mask);
for (i=0; i<EVENT_NUM; i++) {
if (event_array[i][0] == '\0') continue;
if (event->mask & (1<<i)) {
printf("Event: %s\n", event_array[i]);
}
}
tmp_len = sizeof(struct inotify_event) + event->len;
event = (struct inotify_event *)(offset + tmp_len);
offset += tmp_len;
}
copy_file(srcname,destname);
}
printf("END len = %d\n",len);
}
void copy_file(char *srcname,char *destname)
{
struct stat stbuf;
if(lstat(srcname,&stbuf)==-1){
fprintf(stderr,"fsize:can't access %s\n",srcname);
return;
}
if((stbuf.st_mode&S_IFMT)==S_IFDIR){
mkdir(destname,0755);
return;
}
int fr,fw,len;
char buf[10]={0};
fr=open(srcname,O_RDONLY);
if(fr<0){
perror("open error");
exit(1);
}
fw=open(destname,O_WRONLY|O_CREAT|O_TRUNC,0644);
if(fw<0){
perror("open error");
exit(1);
}
while((len=read(fr,buf,10))>0)
{
write(fw,buf,len);
}
close(fr);
close(fw);
}