Kutay Demireren
Kutay Demireren

Reputation: 650

fgets only read the first line of file

I am trying to read a file from my .cpp file. I am using C libraries, so do not confuse on that.

So the problem is as clear as what I said in the title. fgets method can read the first line but when it comes to the second line, it cannot read neither the second line nor the rest of the file (since it exits when a problem occurs).

You can find the associated part of code:

void read_input()
{
      int i = 0, N = 5;
  char str[STR_SIZE], line[STR_SIZE];
  FILE *fp;

  fp = fopen("out", "r");
  if (!fp)
    {
      fprintf(stderr, "error: file could not be opened\n");
      exit(1);
    }

  for (i = 0; i<2; i++)
    {
      if (fgets(str, STR_SIZE, fp) == NULL)
        {
          fprintf(stderr, "error: failed at file reading\n");
          exit(1);
        }

      if (feof(fp))
        {
          fprintf(stderr, "error: not enough lines in file\n");
          exit(1);
        }

      if ((sscanf(str, "%s", line) != 1) )
        {
          fprintf(stderr, "error: invalid file format\n");
          exit(1);
        }
      printf("%d\t%s\n", i, line);
      fclose(fp);
    }
}

Upvotes: 0

Views: 4327

Answers (2)

fluter
fluter

Reputation: 13786

You are closing the file in the loop! Put the fclose function outside of the loop.

for (i = 0; i<2; i++)
{
    ....
    printf("%d\t%s\n", i, line);
    fclose(fp); // <-- here, move out of the loop.
}

Upvotes: 3

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

I believe, the problem is there, because you've used fclose(fp); inside the loop. So, after the very first iteration, the fp is passed to fclose() and for any recurring use of fp in any further iteration will invoke undefined behavior as the fp is not valid anymore.

Solution: Move the fclose(fp); outside the loop.

Upvotes: 6

Related Questions