Thread: Read a file Twice!

  1. #1
    Registered User
    Join Date
    Dec 2011
    Posts
    2

    Read a file Twice!

    I 've been searching all over the internet for a way to read a file twice but all the results i could find were about c++ or were talking about a rewind() function which doesn't work for me. so any suggestions of how i can reset the *fp?

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    rewind() was made for that purpose!

    If for some reason you don't like it, you can always close, and then reopen the file, same as the first time.

    fclose(fp), then fopen, just like before.

    A third option would be to use fseek(), but that's no better than rewind().

  3. #3
    Registered User
    Join Date
    Nov 2011
    Posts
    32
    Quote Originally Posted by fraudaroulis View Post
    I 've been searching all over the internet for a way to read a file twice but all the results i could find were about c++ or were talking about a rewind() function which doesn't work for me. so any suggestions of how i can reset the *fp?
    use either
    Code:
    (void) fseek(stream, 0, SEEK_SET)
    or
    Code:
    rewind(fp);
    The above two functions will point to the initial position of a FILE. By incrementing current pointer you can read the file again. [edited]
    Last edited by chibi.coder; 12-19-2011 at 02:59 PM.

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Given that both fseek() and rewind() work only on opened files... No, there's no need to open the file again...

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > A third option would be to use fseek(), but that's no better than rewind().
    Except that rewind() will also clear the eof condition, if you read to the end of the file.

    rewind(3): reposition stream - Linux man page
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Basic file read, file write program
    By starwarsyeah in forum C++ Programming
    Replies: 5
    Last Post: 02-28-2011, 03:23 PM
  2. Open a file, read it ... and ... read it again
    By Tiago in forum C Programming
    Replies: 1
    Last Post: 04-17-2010, 03:32 AM
  3. File Handling -Read write and edit a file
    By aprop in forum C Programming
    Replies: 3
    Last Post: 02-27-2010, 02:01 PM
  4. How can I know the actual bytes read in a file read
    By pliang in forum C++ Programming
    Replies: 1
    Last Post: 06-08-2005, 04:23 PM