Re: [C++] Rewinding an isteam and GNU G++

From: Alwyn (dt015a1979_at_mac.com.invalid)
Date: 11/01/04


Date: Mon, 01 Nov 2004 11:52:59 +0000

In article <4185A368.4020605@sbcglobal.net>, Thomas Matthews
<Thomas_MatthewsSpamBotsSuck@sbcglobal.net> wrote:
>
> {
> // The G++ compiler always comes here.
> cerr << "getline after rewind failed." << endl;
> }
>
> return EXIT_SUCCESS;
> }

It works for me.

$ cat rewind.cc
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>

using namespace std; // for this example.

int main(void)
{
  ifstream inp("my_data.txt");
  string text_line;

  // Read the entire data file
  // and send to cout.
  while (getline(inp, text_line))
    {
      cout << text_line << endl;
    }

  // Now, the inp file is in an error
  // state, so clear it before positioning.
  inp.clear();

  // At this point, G++ reports that inp is
  // in a good state {inp.good() == true}.

  // Rewind the file.
  inp.seekg(0);

  // At this point, G++ reports that inp is
  // in a failed state (inp.fail() == true).
  // However, Borland compiler reports that
  // inp is in a good state.

  // Clear the state after rewinding.
  // This is primarily for G++.
  inp.clear();

  // Read {the first} line of text.
  if (getline(inp, text_line))
    {
      cout << text_line << endl;
    }
  else
    {
      // The G++ compiler always comes here.
      cerr << "getline after rewind failed." << endl;
    }

  return EXIT_SUCCESS;
}
$ g++ -v
Reading specs from /usr/libexec/gcc/darwin/ppc/3.3/specs
Thread model: posix
gcc version 3.3 20030304 (Apple Computer, Inc. build 1666)
$ g++ -g -o rewind rewind.cc
$ cat my_data.txt
Here are some lines
of text.
82-35-95-10:~/Scrap alwyn$ ./rewind
Here are some lines
of text.
Here are some lines

Alwyn



Relevant Pages