freopen & cout

Alex Vinokur alexvn@connect.to
Tue Dec 2 18:27:00 GMT 2003


Hi,

Where has output-to-cout gone in the program below?

Thanks,

========= C++ code : File foo.cpp : BEGIN =========
#include <cstdio>
#include <cassert>
#include <iostream>
#include <fstream>
using namespace std;

#define FILE_NAME "foobar"

int main ()
{
ofstream ofs;

  remove (FILE_NAME);

  ofs.open (FILE_NAME);
  assert (ofs);
  assert (ofs.is_open());

FILE* stdof = freopen (FILE_NAME, "w", stdout);
  assert (stdof);

  cout << "to cout (first time)" << endl;   // Problematic line
  ofs  << "to ofs  (first time)" << endl;
  cout << "to cout (second time)" << endl;  // Problematic line
  ofs  << "to ofs  (second time)" << endl;

  ofs.close();
  assert (!ofs.is_open());

int rc = fclose (stdof);
  assert (!rc);

  return 0;
}
========= C++ code : File foo.cpp : END ===========


========= Compilation & Run : BEGIN =========

$ g++ -v
[---omitted---]
gcc version 3.3.1 (cygming special)

$ g++ -W -Wall foo.cpp

$ a
// No output; Where has output-to-cout gone?

$ cat foobar
to ofs  (first time)
to ofs  (second time)

========= Compilation & Run : END ===========


--
   =====================================
   Alex Vinokur
     mailto:alexvn@connect.to
     http://up.to/alexvn
   =====================================











More information about the Gcc-help mailing list