#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
int main()
{
int status = 0;
FILE * fPointer;
FILE * gPointer;
fPointer = fopen("file1.txt", "r");
gPointer = fopen("file2.txt", "r");
char singleLine[150];
char secondLine[150];
while(fgets(singleLine,150,fPointer)!=NULL && fgets(secondLine,150,gPoi$
{
//fgets(singleLine,150,fPointer);
//fgets(secondLine,150,gPointer);
printf("singleLine: %s\n",singleLine);
printf("secondLine: %s\n",secondLine);
if (singleLine != secondLine)
{
status = 1;
}
}
printf("final status: %d\n", status);
if (status == 0)
{
printf("same\n");
}
else if (status == 1)
{
printf("not same\n");
}
fclose(fPointer);
fclose(gPointer);
return 0;
}
The contents of both files are "hello" and "hello". But for some reason the output I get is
singleLine: hello
secondLine: hello
final status: 1
which equals "not the same".
I checked by printing what singleLine
and secondLine
are at each iteration and they are the same.
What am I doing wrong?
The following doesn't quite work as you think it does:
if (singleLine != secondLine)
That is because singleLine
and secondLine
are arrays (treated as strings). Equality/inequality operators in C, when used for arrays, simply check whether the two arrays reside at the same address in memory (i.e. are the same variable). Which in your case are not, so your if statement is always true.
Since you are treating both arrays as strings, the correct function to use is strcmp
or strncmp
, both defined in <string.h>
. This is the standard way of performing string comparisons in C (hence the name of the functions).
Your if statement, in this case should be:
if (strcmp(singleLine, secondLine) != 0)
{
status = 1;
}