Thread: Reset fgets to read from the beginning of a file?

  1. #1
    Awesomefaceradcore bivhitscar's Avatar
    Join Date
    Apr 2006
    Location
    Melbourne, Australia
    Posts
    210

    Reset fgets to read from the beginning of a file?

    Well, I need to read a file (containing only float values) to check how many lines it contains - easy, using fgets. Then I need to malloc a float array to hold the values, also easy. And here is where I'm stuck: I need to read the file again to obtain the values and fill the array.

    However, subsequent calls to fgets after the complete file has been read, return NULL - which I kinda understand why. Is there any way to 'reset' fgets to read from the start again; without closing the file and re-opening it?
    it's ironic considerate rarity patron of love higher knowledge engulfs me...

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Try using rewind(FILE *stream);
    Basically after you get done counting lines, rewind it, and read again into the array. This function also resets error flags on the stream so you shouldn't have problems reading it again.
    Last edited by whiteflags; 05-20-2006 at 11:39 PM.

  3. #3
    Awesomefaceradcore bivhitscar's Avatar
    Join Date
    Apr 2006
    Location
    Melbourne, Australia
    Posts
    210
    Awesome, works perfectly. Thanks mate.
    it's ironic considerate rarity patron of love higher knowledge engulfs me...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. read from file problem
    By Martin Kovac in forum C Programming
    Replies: 1
    Last Post: 04-13-2009, 08:33 AM
  2. sequential file program
    By needhelpbad in forum C Programming
    Replies: 80
    Last Post: 06-08-2008, 01:04 PM
  3. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  4. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  5. Replies: 3
    Last Post: 03-04-2005, 02:46 PM