LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C - How do I return to the beginning of a file I'm reading? (https://www.linuxquestions.org/questions/programming-9/c-how-do-i-return-to-the-beginning-of-a-file-im-reading-850571/)

golmschenk 12-16-2010 01:30 AM

C - How do I return to the beginning of a file I'm reading?
 
I'm reading a text file with fscanf using a loop until feof(inFile). How can I return to the top of the file? As in I have one loop that scans until the eof and then after it there's another loop and I want to start from the beginning of the file again scanning to the end of it. How do I get back there?

Thanks!

macemoneta 12-16-2010 01:36 AM

You can reposition in the open file:

Code:

// to reset current position to beginning of file
  void rewind(FILE *f); 

  rewind(infile);

Or you can just close and reopen the file.

golmschenk 12-16-2010 01:56 AM

Great, thank you much!

theNbomr 12-16-2010 08:52 AM

Just a bit of possibly useful information...
If you open the file as a stream ( fopen() ), you have even more flexibility. You can get the current position within a file at any time with ftell(), and reset the current position to arbitrary values with fseek(). The arguments to fseek() allow you to specify a position relative to the beginning of the file, relative to the end of the file, or relative to the current position.

--- rod.

EDIT: Oops. I see you must already have opened the file with fopen().


All times are GMT -5. The time now is 01:15 PM.