I'm currently trying to make a program that compare 2 files and that show all the differences.
The problems I'm having are:
First line of the result doesn't show the first character.
The differences don't have right results.
I've two input files.
file.txt
AAA
BBB
CCC
DDD
EEE
file2.txt
AAA
111
BBB
222
333
CCC
DDD
EEE
444
The output (1st line is bugged) I'm getting is:
11
BBB
222
333
CCC
And the output (without the 1st line bug) I desire to get must be:
111
222
333
444
This is currently my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int compare(char *fname1, char *fname2)
{
FILE *fp1 = fopen(fname1, "r");
FILE *fp2 = fopen(fname2, "r");
int ch1, ch2;
if (fp1 == NULL)
{
printf("Can't open %s", fname1);
exit(1);
}
else if (fp2 == NULL)
{
printf("Can't open %s", fname2);
exit(1);
}
else
{
ch1 = getc(fp1);
ch2 = getc(fp2);
while ((ch1 != EOF) && (ch2 != EOF) && (ch1 == ch2))
{
ch1 = getc(fp1);
ch2 = getc(fp2);
}
if (ch1 == ch2)
{
printf("Same. \n");
}
else if (ch1 != ch2)
{
printf("Different strings:\n");
while(!feof(fp1) && !feof(fp2))
{
fgets(fname1, ch1, fp1);
fgets(fname2, ch2, fp2);
if(strcmp(fname1, fname2) != 0)
{
printf("%s", fname2);
}
}
}
}
fclose(fp1);
fclose(fp2);
return 0;
}
And the main function:
int main(int argc, char *argv[])
{
if (argc == 3){
compare(argv[1], argv[2]);
}else{
printf("Usage: ./what file.txt file2.txt \n");
}
return 0;
}
Comparing file.txt and file2.txt or file2.txt and file.txt should give the same result.