我正在编写一个程序来比较两个文件。如果出现匹配行,则程序将继续执行某些任务。我的第二个文件只有一行,第一个文件有几行
File_1 的内容
apple is red
oranges are orange
banana is yellow
cat is black
red is not green
File_2 的内容
cat is black
我已经使用 fscanf
函数读取 File_2 的行并将其存储在一个变量中。
if ((fp=fopen(File_2, "r")) == NULL)
{
printf("Error opening File");
}
fscanf(fp,"%[^\n]", name);
fclose(fp);
我已经使用以下方法在 File_1 中搜索相似点
fp = fopen(File_1, "r");
while ((read = getline(&line, &len, fp)) != -1)
{
if (strcmp(line,name)==0)
{
printf("Hurray\n");
break;
}
else
{
printf("I am unlucky\n");
}
}
fclose(fp);
但我的问题是,
strcmp()
is not returning0
我想知道这里出了什么问题。如有任何建议,我们将不胜感激。
最佳答案
我已经设法修复了它。
使用以下方式删除包含在 getline()
中的换行符:
fp = fopen(File_1, "r");
while ((read = getline(&line, &len, fp)) != -1)
{
line[strcspn ( line, "\n" )] = '\0'; \\ will drop the newline character
if (strcmp(line,name)==0)
{
printf("Hurray\n");
break;
}
else
{
printf("I am unlucky\n");
}
}
fclose(fp);
我希望有更好的方法来做到这一点。
感谢 ggorlen、user3386109 和 WhozCraig 提供的调试技巧。也由 Nayantara Jeyaraj 编辑。
关于在 C 编程中比较两个文件以匹配行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56267913/