This is a C program that's being written with a Linux shell. The goal is to compare two different directories and report what is NEW, MODIFIED, or DELETED.
I'm stuck on the figuring out whether a file exists in the base directory but not the modified directory, in which case the file name should be printed to the screen along with the message DELETED.
I've already figured out the NEW and MODIFIED for the most part. Sub directories aren't supposed to be printed out but I can't resolve that either.
Can anyone help point me in the right direction? Here's the code I have so far.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
int main(int argc, char ** argv)
{
int recurse = 0;
int diff = 0;
char * basedir = NULL;
char * moddir = NULL;
int i;
for (i = 1; i < argc; i++)
{
if (argv[i][0] == '-')
{
if (strcmp(argv[i], "-R") == 0)
{
recurse = 1;
}
else if (strcmp(argv[i], "-D") == 0)
{
diff = 1;
}
else
{
printf("error: invalid option %s\n", argv[i]);
exit(-1);
}
}
else
{
if (basedir == NULL)
{
basedir = argv[i];
}
else if (moddir == NULL)
{
moddir = argv[i];
}
else
{
printf("error: invalid argument %s\n", argv[i]);
exit(-2);
}
}
}
if ((basedir == NULL) || (moddir == NULL))
{
printf("error: must pass both basedir and moddir\n");
exit(-3);
}
DIR * moddir_contents = opendir(moddir);
if (moddir_contents != NULL)
{
struct dirent * moddir_entry = readdir(moddir_contents);
while (moddir_entry != NULL)
{
DIR * basedir_contents = opendir(basedir);
if (basedir_contents != NULL)
{
int matched = 0;
int deleted = 0;
struct dirent * basedir_entry = readdir(basedir_contents);
while (basedir_entry != NULL)
{
if (strcmp((*moddir_entry).d_name, (*basedir_entry).d_name) == 0)
{
matched = 1;
struct stat buf;
time_t mod_stamp;
char modfilename[1024];
strcpy(modfilename, moddir);
strcat(modfilename, "/");
strcat(modfilename, (*moddir_entry).d_name);
if (stat(modfilename, &buf) == 0)
{
mod_stamp = buf.st_mtime;
}
else
{
printf("error: failed to get modified time for file %s\n", (*moddir_entry).d_name);
exit(-5);
}
time_t base_stamp;
char basefilename[1024];
strcpy(basefilename, basedir);
strcat(basefilename, "/");
strcat(basefilename, (*basedir_entry).d_name);
if (stat(basefilename, &buf) == 0)
{
base_stamp = buf.st_mtime;
}
else
{
printf("error: failed to get modified time for file %s\n", (*basedir_entry).d_name);
exit(-5);
}
if (mod_stamp > base_stamp)
{
printf("%s MODIFIED!\n", (*moddir_entry).d_name);
}
}
basedir_entry = readdir(basedir_contents);
}
if (matched == 0)
{
printf("%s NEW\n", (*moddir_entry).d_name);
}
closedir(basedir_contents);
}
else
{
printf("error: failed to open basedir %s\n", basedir);
exit(-5);
}
moddir_entry = readdir(moddir_contents);
}
closedir(moddir_contents);
}
else
{
printf("error: failed to open moddir %s\n", moddir);
exit(-4);
}
return 0;
}