Why wont the program read from the 2 argument file

2019-09-16 12:16发布

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

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

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

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

标签: c linux string
2条回答
forever°为你锁心
2楼-- · 2019-09-16 12:58

You should open a file and then read bytes from that file into temporary buffer:

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)
}

If you want to search for string/pattern in a file, be aware that looked pattern in file may cross your chunk-size boundary, for example: you look for "hello", and BUFSIZ is 512. File contains "hello" at byte 510. Obviously, if you read by 512, you will get the first chunk ending with "he", and the second chunk starting with "llo". Probability of this situation is nonzero for all chunk sizes (except SIZE_MAX, but that buffer size is impossible by other reasons). Dealing with borders may be very complicated.

查看更多
祖国的老花朵
3楼-- · 2019-09-16 13:11

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.

查看更多
登录 后发表回答