#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;
}
两个文件的内容均为“ hello”和“ hello”。但是由于某种原因,我得到的输出是
singleLine:您好secondLine:您好最终状态:1
等于“不一样”。我通过打印每次迭代中的singleLine
和secondLine
来检查它们是否相同。
我在做什么错?
以下内容并不像您认为的那样有效:
if (singleLine != secondLine)
这是因为singleLine
和secondLine
是数组(视为字符串)。 C中的相等/不相等运算符用于数组时,只需检查两个数组是否位于内存中的同一地址(即是相同的变量)即可。在您的情况下,哪个不是,所以您的if语句始终为true。
由于将两个数组都视为字符串,因此要使用的正确函数是strcmp
或strncmp
,两者均在<string.h>
中定义。这是在C中执行字符串比较的标准方法(因此称为函数名)。
您的if语句,在这种情况下应该是:
if (strcmp(singleLine, secondLine) != 0)
{
status = 1;
}