为什么惯于从2参数文件中读取的程序? [英] Why wont the program read from the 2 argument file?

查看:89
本文介绍了为什么惯于从2参数文件中读取的程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,分配是实现使用输入文件子字符串搜索程序,从搜查,被搜索的输入。我创建了以下code:

So the assignment is to implement a substring search program using an input file to be searched from and an input to be searched. I created the following code:

#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终端为:

The program compiles but when i go to implement it in the ubuntu terminal as:

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

为什么心不是使用的第一个参数的程序(的argv [1])作为测试版和第二个参数(argv [2])为正确?

Why isnt the program using the first argument (argv[1]) as beta and the second argument (argv[2]) as a correctly?

推荐答案

关闭......但是这是更接近:

Close...but this is closer:

#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;
}

的主要区别是,这种循环读从输入文件多行。你会只输入单行文件上工作。

The main difference is that this loops reading multiple lines from the input file. Yours would only work on files with a single line of input.

这篇关于为什么惯于从2参数文件中读取的程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆