【问题标题】:Why is fgets not reading after the first line?为什么 fgets 在第一行之后不读取?
【发布时间】:2016-05-01 05:23:40
【问题描述】:

我有一个文本文件,文本文件的每一行包含 3 个整数,如下所示。

8 168 0
10 195 0
4 71 0
16 59 0
11 102 0
...

因为文件很大,我想用 fseek 和 fgets 写一个可以返回文件中任意行的函数。在这个example之后,我写了一个看起来像这样的函数:

/* puts example : hello world! */
#include <stdio.h>

int main ()
{      
  FILE* pFile;
  char mystring [10];

  pFile = fopen ("in/data_3" , "r");
  fseek(pFile, 3, SEEK_SET);
  if ( fgets (mystring , 10 , pFile) != NULL ){
    puts (mystring);
  }

  fclose (pFile);
}

但是,上面的程序返回68 0。当我更改为fseek(pFile, 7, SEEK_SET); 时,它不会返回任何内容。当我更改为fseek(pFile, 10, SEEK_SET); 时,它返回195 0。似乎每行中的字符数不固定,换行符不能返回超过 1 行。如何编写函数,使其返回完整的行而不知道整数的大小(可以是 0 到数千)?

【问题讨论】:

  • 我认为你必须通读整个文件,直到你到达你想要的行。你能做的不多
  • "当我更改为fseek(pFile, 7, SEEK_SET); 时,它不会返回任何内容。"你确定吗?应该返回两个换行符。
  • 是的,我只是运行程序。它不返回任何换行符。有什么我错过的吗?
  • 请注意 fseek 的参数是字节,而不是行。当您意识到它是字节时,所有结果都是有意义的。
  • 如果您将输入文件的格式设置为恒定的行长度,您就可以通过fseek(pFile, line_number * (LINE_LENGTH + END_OF_LINE_LENGTH), SEEK_SET); 查找该行

标签: c io fgets fseek


【解决方案1】:

如何编写函数,使其返回完整的行而不知道整数的大小(可以是 0 到数千)?

编写一个可以跳过N行数的函数。

void skipLines(FILE* in, int N)
{
   char line[100]; // Make it as large as the length of your longest line.
   for ( int i = 0; i < N; ++i )
   {
      if ( fgets(line, sizeof(line), in) == NULL )
      {
         // N is larger than the number of lines in the file.
         // Return.
         return;
      }
   }
}

然后将其用作:

pFile = fopen ("in/data_3" , "r");
skipLines(pFile, 3);
if ( fgets (mystring , 10 , pFile) != NULL ){
  puts (mystring);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-15
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多