【问题标题】:Why wont the program read from the 2 argument file?为什么程序不会从 2 参数文件中读取?
【发布时间】:2014-02-08 21:56:37
【问题描述】:

所以任务是使用要搜索的输入文件和要搜索的输入来实现一个子字符串搜索程序。我创建了以下代码:

#include <stdio.h>
#include <string.h>

int main(int argc,char *argv[])
{
  FILE *fp;
  fp = fopen(argv[1],"r");
  if (fp == NULL)
    {
      printf("Error");
      return 0;
    }
  char* tmpp[100];
  int count = 0;
  char* nexts = argv[2];
  char* tmp = fgets(tmpp,100,fp);
  while(tmp = strstr(tmp,nexts))
    {
      count++;
      tmp++;
    }
  printf("%d\n\n",count);
  fclose(fp);

  return 0;
}    

程序可以编译,但是当我在 ubuntu 终端中实现它时:

echo "aabb" >beta
./a.out beta a
1

为什么程序没有正确使用第一个参数 (argv[1]) 作为 beta 而第二个参数 (argv[2]) 作为一个?

【问题讨论】:

  • 您将argv[1] 分配给tmp,因此您要在单词beta 中查找字母a。听起来您想改为从使用 fopen 打开的文件中读取数据,因此您需要将 fread 该数据放入 char 数组并使用 strstr 搜索 THAT。
  • 正如乔所说,你需要从文件中读取数据(fgets() 可能是你这里的朋友),然后计算你从文件中读取的字符数。目前,您正在扫描文件名,而不是文件内容。 (试试echo "xxyyzz" &gt; omega; ./a.out omega z。)
  • 我该怎么做?我是 C 新手,所以我不明白 fread 在这种情况下是如何工作的?
  • 约翰,我尝试使用 omega 和 z,但返回的是 0
  • 如果我在这种情况下使用'fgets()',我是否必须将它应用于两个参数?

标签: c linux string


【解决方案1】:

您应该打开一个文件,然后将该文件中的字节读入临时缓冲区:

FILE *file = fopen("file", "r");
while (1) {
    char buffer[BUFSIZ+1];
    size_t nread = fread(buffer, 1, sizeof(buffer)-1, file);
    if (nread == 0) break; // read error or EOF
    buffer[nread] = 0;

    // chunk with BUFSIZ amount of bytes is available via buffer (and is zero-terminated)
}

如果您想在文件中搜索字符串/模式,请注意文件中查找的模式可能会跨越您的块大小边界,例如:您查找“hello”,而 BUFSIZ 为 512。文件包含“hello " 在字节 510 处。显然,如果您读取 512,您将得到第一个以“he”结尾的块,第二个以“llo”开头的块。这种情况的概率对于所有块大小都是非零的(除了 SIZE_MAX,但由于其他原因,那个缓冲区大小是不可能的)。处理边界可能非常复杂。

【讨论】:

    【解决方案2】:

    关闭...但这更接近:

    #include <stdio.h>
    #include <string.h>
    
    int main(int argc, char *argv[])
    {
      if (argc != 3)
      {
        fprintf(stderr, "Usage: %s file pattern\n", argv[0]);
        return 1;
      }
      FILE *fp = fopen(argv[1], "r");
      if (fp == NULL)
      {
        fprintf(stderr, "Error: failed to open file %s for reading\n", argv[1]);
        return 1;
      }
      char tmpp[1000];
      int count = 0;
      char* nexts = argv[2];
      while (fgets(tmpp, sizeof(tmpp), fp) != 0)
      {
        char *tmp = tmpp;
        while ((tmp = strstr(tmp, nexts)) != 0)
        {
          count++;
          tmp++;
        }
      }
      printf("%d\n", count);
      fclose(fp);
    
      return 0;
    }
    

    主要区别在于这个循环从输入文件中读取多行。您的只能处理具有单行输入的文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-12
      相关资源
      最近更新 更多