在 C 编程中比较两个文件以匹配行

标签 c string scanf getline strcmp

我正在编写一个程序来比较两个文件。如果出现匹配行,则程序将继续执行某些任务。我的第二个文件只有一行,第一个文件有几行

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 returning 0

我想知道这里出了什么问题。如有任何建议,我们将不胜感激。

最佳答案

我已经设法修复了它。 使用以下方式删除包含在 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/

相关文章:

c - 文件路径数组中只有一个元素有效 - C

c - 使用fgetc读取文件并将句子添加到链表中

c - 使用 sscanf 匹配零个或多个空格

string - Data.ByteString.Char8中 `isInfixOf`的时间复杂度是O(m * n)吗?

java - 用实际值替换字符串中的变量 - Groovy

c - 为什么我的 C 编译器跳过第二个 scanf?

c - 数组到变量

c - c 中的 do-while 或 scanf() 不起作用

提示时出现 C 无限循环问题

java - 带有java和字符串变量的指针