Question: This task is to design and implement a program to watch a directory. Your program will monitor a directory and print out a message for
This task is to design and implement a program to watch a directory. Your program will monitor a directory and print out a message for each of the following activity: 1. A file is added. 2. A file is deleted. 3. A file is renamed. Start with this source file Name your program watchdir.c. Your program is an infinite loop that take a snapshot of the watched directory every 1 seconds. The snapshot consists of all pairs of inode numer and name. Compare the current snapshot with the previous snapshot and see what have changed. You can have two putty terminals opened. One terminal is running watchdir. In other terminal, you will add, delete and rename files. You willl need to use strcmp() to compare two strings (filenames). Your program should work like this.
Here is the given code to build on.
#include#include #include #include #include #include int main(int argc, char *argv[]) { if(argc!=2) return 1; //malloc to arrays of directory entry struct dirent *old = malloc(sizeof(struct dirent)*100); struct dirent *new = malloc(sizeof(struct dirent)*100); int old_count, new_count; struct dirent *result; char *path = argv[1]; /*Read in the snapshot of the directory Store all entries in old array */ DIR *dir = opendir(path); if(dir==NULL){ fprintf(stderr, "Cannot open dir %s: %s ", path, strerror(errno)); return -2; } //number of entries old_count=0; while(1){ readdir_r(dir, &(old[old_count]), &result); if(result==NULL) break; //add printf to print out the inode # and filename here to see the content old_count++; } closedir(dir); while(1){ sleep(1); /*Read in the new snapshot of the directory Store all entries in new array */ dir = opendir(path); if(dir==NULL){ fprintf(stderr, "Cannot open dir %s: %s ", path, strerror(errno)); return -2; } //number of entries new_count = 0; while(1){ readdir_r(dir, &(new[new_count]), &result); if(result == NULL) break; //add printf to print out the inode # and filename here to see the content new_count++; } closedir(dir); /*Need to compare the new snapshot with the old snapshot Probally need a few nested for loops here To check for new file(s), deleted file(s) and file(s) with new name */ /*Before the next iteration Need to swap the snapshot, the new snapshot is now old */ } return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
