Hey guys, I'm currently trying to implement a function using C that takes in two file names as command line arguments and compare them lexicographically.
The function will return -1 if the contents of the first file are less than the contents of the second file, 1 if the contents of the second file are less than the contents of the first file, and 0 if the files are identical.
Please give me some advice on how I should start with this.
[EDIT]
Hey guys sorry if there's any unclear part in the question, so I'll just post the link to the question here: Original question. Thing is it's an uni assignment so we're expected to do it using only basic C properties, probably only including stdio.h, stdlib.h, and string.h. Sorry for the trouble caused. Also here's the code I already have, my main problem now is that the function doesn't know that file1.txt (refer to the link) has it's first line longer than file2.txt, but is actually lexicographically less:
int filecmp(char firstFile[], char secondFile[])
{
int similarity = 0;
FILE *file1 = fopen(firstFile, "r");
FILE *file2 = fopen(secondFile, "r");
char line1[BUFSIZ];
char line2[BUFSIZ];
while (similarity == 0)
{
if (fgets(line1, sizeof line1, file1) != NULL)
{
if (fgets(line2, sizeof line2, file2) != NULL)
{
int length;
if (strlen(line1) > strlen(line2))
{
length = strlen(line1);
}
else
{
length = strlen(line2);
}
for (int i = 0; i < length; i++)
{
if (line1[i] < line2[i]) similarity = -1;
if (line1[i] > line2[i]) similarity = 1;
}
}
else
{
similarity = 1; //As file2 is empty
}
}
else
{
if (fgets(line2, sizeof line2, file2) != NULL)
{
similarity = -1; // As file1 is empty
}
else break;
}
}
fclose(file1);
fclose(file2);
return similarity;
}
[END EDIT]
Many thanks,
Jonathan Chua