GeekInterview.com
   Home |  Tech FAQ  |   Interview Questions |  Placement Papers |  Tech Articles |  Learn |  Freelance Projects |  Online Testing |  Geeks Talk |  Job Postings |  Knowledge Base | Site Search |  Add/Ask Question

  GeekInterview.com  >  Interview Questions  >  Programming  >  C

 Print  |  
Question:  Compare Two Files in C

Answer: Write a program that compares two files and return 0 if they are equal and 1 if they are not equal.


January 01, 2009 16:58:56 #2
 chamkila   Member Since: January 2009    Total Comments: 1 

RE: Compare Two Files in C
 

/* here is a very basic program to compare files - chamkila! */
#include
#include
#include

#define ANSI
#ifdef ANSI /* ANSI compatible version */
#include
void closeFiles(FILE* fh, ...);
#else /* UNIX compatible version */
#include
void closeFiles(va_list);
#endif

int compareFiles(char[], char[]);
void printUsage(void);
void displayError(void);

int main (int argc, char* argv[])
{
int rc = errno;
if (argc < 3)
{
printUsage();
return -1;
}
rc = compareFiles(argv[1], argv[2]);
printf("%s: %dn", rc ? "failed" : "success");
return 0;
}

int compareFiles(char arg1[], char arg2[])
{
FILE* fh1 = NULL;
FILE* fh2 = NULL;
char buf1[BUFSIZ] = {''};
char buf2[BUFSIZ] = {''};

if (strlen(arg1) <= 0 || strlen(arg2) <= 0)
{
printUsage();
return -1;
}
if (NULL == (fh1 = fopen(arg1, "r")) || NULL == (fh2 = fopen(arg2, "r")))
{
displayError();
return -1;
}

while (!feof(fh1) && !feof(fh2))
{
fgets(buf1, BUFSIZ - 1, fh1);
fgets(buf2, BUFSIZ - 1, fh2);
if (0 != strcmp(buf1, buf2))
{
printf("file '%s' and file '%s' don't matchn", arg1, arg2);
closeFiles(fh1, fh2);
return -1;
}
else
{
continue;
}
}
printf("file '%s' and file '%s' matchn", arg1, arg2);
closeFiles(fh1, fh2);
return 0;
}

void printUsage(void)
{
printf("usage: fcmp.exe , nn");
}

void displayError()
{
printf("error: %sn", strerror(errno));
return;
}

#ifdef ANSI /* ANSI compatible version */
void closeFiles(FILE* fh, ...)
{
FILE* f = NULL;
va_list argptr;

va_start(argptr, fh);
f = va_arg(argptr, FILE*);
if (NULL != f)
{
fclose(f);
}
va_end (argptr);

return;
}
#else /* UNIX compatible version must use old-style definition. */
void closeFiles(va_alist)
{
FILE* f = NULL;
va_list argptr;

va_start(argptr);
f = va_arg(argptr, FILE*);
if (NULL != f)
{
fclose(f);
}
va_end (argptr);
return;
}
#endif

     

 

Back To Question