• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 948
  • Last Modified:

Restarting ifstream input

I have an input file and I want to restart it at the end of a loop and reopen it at the beginning.

ifstream input(infile.c_str());

When I get to the end, what is the best way to start back at the top of the file?

I tried input.close(); and then ifstream input(infile.c_str()); and that does not work.

I know this is probably a really easy question but I can't seem to find the answer anywhere and its not coming to me.

Thanks

0
Ant_Dogg
Asked:
Ant_Dogg
  • 2
  • 2
  • 2
1 Solution
 
HendrikTYRCommented:
input.close();
input.open(infile.c_str());

Regards
Hendrik
0
 
IndrawatiCommented:
There are two ways to do it:
1. If you want to close and reopen, you can do:

input.close();
input.open(infile.c_str());

2. After you reach the end of the file, you can do:

input.seekg(0);
or
input.seekg(0, std::ios_base::beg);
0
 
Ant_DoggAuthor Commented:
I tried both of those:

      input.seekg(0);

      if (input.eof( ))
      {exit(1);}

and the program closes.  any ideas on what I'm doing wrong?  I tried the same thing with input.close and input.open.

Thanks
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
HendrikTYRCommented:
post some code
0
 
IndrawatiCommented:
There's nothing wrong with your code. fstream::eof() returns true whenever the stream has ever encountered end-of-file. Even if you open and close or seek the stream, ieof() will still return true if the stream has encountered end of file before. To clear it, you can call ifstream::clear().
0
 
Ant_DoggAuthor Commented:
That was the problem exactly.  Thank you, Indrawati
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

  • 2
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now