Jump to content
  • Advertisement
Sign in to follow this  
Shuger

streaming to file

This topic is 4413 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello everybody! I need to stream the input to the program from the txt file, and back from a program to another txt file. The problem is that i need to process input & output with cin.get(), and cout.put(). I was told it should be possible to do. I'm using dev-cpp.

Share this post


Link to post
Share on other sites
Advertisement
Running from the command line you can use redirection to get what you want.

See here to see how.

If you want to do it programmatically instead you must replace all references to std::cin and std::cout with a std::ifstream and std::ofstream

Share this post


Link to post
Share on other sites
If you absolutely have to use cin and cout and redirect it programatically, you can replace the stream buffers. If I'm not mistaken, the member function rdbuf will get/set the stream buffer.

ifstream is("in.txt");
ofstream os("out.txt");

// use cin/cout from/to file instead of console
streambuf *cin_old = cin.rdbuf(is.rdbuf());
streambuf *cout_old = cout.rdbuf(os.rdbuf());

// restore old stream buffers
cin.rdbuf(cin_old);
cout.rdbuf(cout_old);

The no-parameter version returns a pointer to the stream buffer, while the single parameter version sets the stream buffer. Everything you stream to cout will be passed to os's stream buffer, which means it end up in the file out.txt and not on the console. Similar for cin.

edit: Might want to save and restore stream buffers too. Edited the source.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!