I know how to check if two files have the same content. I made it using fopen and fread. However, I have some problems translating the code and use open and read instead of fopen and fread.
When I run the program like this: ./app file1.txt file2.txt (and files are not equal) program shows the message that they are not equal, and thats perfectly correct. When I try ./app file1 file1 instead, it also shows that the files are NOT equal, which is not true for sure. Another thing is that using Code::Blocks it shows me the return code 255 so I thing I messed something up, but do not what exactly.
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
int CompareFileByteByByte(char *file1, char *file2)
{
int results = 0, c1, c2, br1, br2;
int fin1 = -1, fin2 = -1;
fin1 = open(file1, O_RDONLY);
fin2 = open(file2, O_RDONLY);
if (fin1 == -1)
{
perror ("open");
return -1;
}
if (fin2 == -1)
{
perror ("open");
return -1;
}
br1 = read (fin1, &c1, 1);
br2 = read (fin2, &c2, 1);
while((br1 > 0) && (br2 > 0) && results)
{
br1 = read (fin1, &c1, 1);
br2 = read (fin2, &c2, 1);
results = (c1 == c2);
printf("%c %c\n", c1, c2);
}
close(fin1);
close(fin2);
return results;
}
int main(int argc, char **argv)
{
if(argc < 3)
{
printf("Example usage:\n\n\t %s file1 file2\n\n", argv[0]);
exit(-1);
}
else
{
printf("%s %s\n", argv[1], argv[2]);
if(CompareFileByteByByte(argv[1], argv[2]))
{
printf("Files are equal\n");
}
else
{
printf("Files are NOT equal\n");
}
}
return 0;
}
c1andc2bycharand notint