简体   繁体   English

fgets只读取文件的第一行

[英]fgets only read the first line of file

I am trying to read a file from my .cpp file. 我正在尝试从.cpp文件读取文件。 I am using C libraries, so do not confuse on that. 我正在使用C库,所以不要对此感到困惑。

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). fgets方法可以读取第一行,但是当涉及到第二行时,它既不能读取第二行,也不能读取文件的其余部分(因为发生问题时它会退出)。

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

I believe, the problem is there, because you've used fclose(fp); 我相信问题就在那里,因为您使用过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. 因此,在第一次迭代之后,将fp传递给fclose()并且在任何进一步的迭代中重复使用fp都会调用未定义的行为,因为fp不再有效

Solution: Move the fclose(fp); 解决方案:移动fclose(fp); outside the loop. 在循环之外。

You are closing the file in the loop! 您正在循环中关闭文件! Put the fclose function outside of the loop. fclose函数放在循环之外。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM