简体   繁体   中英

Why is fgets not reading after the first line?

I have a text file, and each line of the text file contains 3 integers, like below.

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

Because the file is big, I wish to use fseek and fgets write a function that can return an arbitrary line in the file. Following this example , I wrote a function that looks like this:

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

However, the above program returns 68 0 . When I change to fseek(pFile, 7, SEEK_SET); , it does not return anything. When I change to fseek(pFile, 10, SEEK_SET); , it returns 195 0 . It seems the number of the characters in each line is not fixed, and the newline somehow cannot return more than 1 line. How can I write the function such that it returns a complete line without knowing the size of the integer (which can be 0 to thousands)?

How can I write the function such that it returns a complete line without knowing the size of the integer (which can be 0 to thousands)?

Write a function that can skip N number of lines.

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

and then use it as:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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