【问题标题】:Comparing two files for matching lines in C Programming在 C 编程中比较两个文件以匹配行
【发布时间】:2019-10-09 14:19:24
【问题描述】:

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

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() 没有返回 0

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

【问题讨论】:

  • 欢迎来到 SO!您是否尝试打印出字符串以查看一个或任何额外字符上是否有尾随换行符?
  • 在调试这样的问题时,打印字符串会有所帮助(如前所述)。请务必在字符串前后放置分隔符,以便您可以看到任何前导或尾随空格。例如:printf("<%s>\n<%s>\n", line, name)
  • 你觉得man page of getline的这一部分可能和它有关吗? : "缓冲区以 null 结尾并且包含换行符"。您正在阅读的名称显然不会,您正在使用设置格式来故意排除它。
  • printf("Error opening File"); - 在这行之后你肯定需要返回或退出

标签: c string scanf getline strcmp


【解决方案1】:

当您使用 getline 读取 File_1 时,您将得到 \n 换行符,正如 WhozCraig 指出的那样。

以下以\0 终止行应该可以解决此问题:

      while ((readlen = getline(&line, &len, fp)) != -1)
          {
             if (line[readlen-1] == '\n')
                 line[--readlen] = '\0';
             if (strcmp(line,name)==0)

【讨论】:

  • read 不是一个好的变量名 - 因为read 也是一个 io 函数
  • 感谢@EdHeal,从原始代码中复制了它,现在更新了变量名。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    相关资源
    最近更新 更多