I am trying to write a function that compares two text files (test1.txt and test2.txt) word by word, the function is supposed to print "files are equal", "files differ: word %d" (if word 13 then past 12 words were equal), and "EOF on [filename]" (the files were equal word by word but one of the files ended before the other).
The problems I am having are:
- the EOF statement only prints if one of the files are completely empty
- the files differ statement only occurs if the first word is different, otherwise it won't print the statement
- the files are equal statment occurs only if the first word for each file are the same
int compare_word(FILE *fp1, FILE *fp2)
{
size_t wordCount = 1;
int isEqual = 1;
unsigned int w1 = 0;
unsigned int w2 = 0;
char word1[LINESIZE];
char word2[LINESIZE];
if(fscanf(fp1, "%s", word1) != EOF)
{
if(fscanf(fp2, "%s", word2) != EOF)
{
}
else
{
isEqual = 0;
printf("EOF on test2.txt");
return 0;
}
}
else
{
isEqual = 0;
printf("EOF on test1.txt");
return 0;
}
for(; w1 < strlen(word1) && w2 < strlen(word2); w1++, w2++)
{
if(word1[w1] != word2[w2])
{
isEqual = 0;
printf("files differ: word %d", wordCount);
return 0;
}
}
wordCount++;
if(isEqual == 1)
{
printf("files are equal");
}
return 0;
}