[ACCEPTED]-freopen() equivalent for c++ streams-io

Accepted answer
Score: 41

freopen also works with cin and cout. No need to search 6 for something new.

freopen("input.txt", "r", stdin); // redirects standard input
freopen("output.txt", "w", stdout); // redirects standard output

int x;
cin >> x; // reads from input.txt
cout << x << endl; // writes to output.txt

Edit: From C++ standard 27.3.1:

The 5 object cin controls input from a stream 4 buffer associated with the object stdin, declared 3 in <cstdio>.

So according to the standard, if we 2 redirect stdin it will also redirect cin. Vice versa 1 for cout.

Score: 14
#include <iostream>
#include <fstream>

int main() {

  // Read one line from stdin
  std::string line;
  std::getline(std::cin, line);
  std::cout << line << "\n";

  // Read a line from /etc/issue
  std::ifstream issue("/etc/issue");
  std::streambuf* issue_buf = issue.rdbuf();
  std::streambuf* cin_buf = std::cin.rdbuf(issue_buf);
  std::getline(std::cin, line);
  std::cout << line << "\n";

  // Restore sanity and read a line from stdin
  std::cin.rdbuf(cin_buf);
  std::getline(std::cin, line);
  std::cout << line << "\n";
}

http://www.cplusplus.com/reference/iostream/ios/rdbuf/

0

Score: 1

This newsgroup posting explores your options.

This 13 is system dependent and the poster didn't 12 indicate the system, but cin.clear() should 11 work. I have tested the attached program 10 on a UNIX system with AT&T version's 9 of iostreams.

#include <iostream.h>
int main()
{
    for(;;) {
        if ( cin.eof() ) {
            cout << "EOF" << endl;
            cin.clear();
        }
        char c ;
        if ( cin.get(c) ) cout.put(c) ;
    }
} 

Yes, that works okay in cfront 8 and TC++. In g++ where the problem first 7 arose an additional action is required:

  cin.clear();
  rewind ( _iob ); // Seems quite out of place, doesn't it?
                   // cfront also accepts but doesn't
                   // require this rewind. 

Though 6 I note that this was in 1991, it should 5 still work. Remember to use the now-standard 4 iostream header, not iostream.h.

(BTW I found that post with 3 the Google search terms "reopen cin 2 c++", second result.)

Let us know how 1 you get on. You could also just use freopen.

More Related questions