By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,972 Members | 1,147 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,972 IT Pros & Developers. It's quick & easy.

Setting a file stream to std[in/out/err]?

P: n/a
In the stdio library, supported by C, we can set a file pointer to
stdin or stdout ot stderr (e.g. FILE* fp = stdin;). Can we do
something similar with ifstream and ofstream in C++? i.e. can we set
the ifstream to stdin and the ofstream to stdout or stderr? If the
answer is yes, please provide a code snippet.

Thanks,
Masood

Aug 15 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On 15 Srp, 06:31, masood.iq...@lycos.com wrote:
In the stdio library, supported by C, we can set a file pointer to
stdin or stdout ot stderr (e.g. FILE* fp = stdin;). Can we do
something similar with ifstream and ofstream in C++? i.e. can we set
the ifstream to stdin and the ofstream to stdout or stderr? If the
answer is yes, please provide a code snippet.

Thanks,
Masood
Do all your stuff in some function or method:

#include <iostream>
#include <fstream>

void DoSomethingWithStream(std::ostream& os)
{
os << "Do something here\n";
}

int main()
{
// You can call DoSomethingWithStream with ostream as well as with
ofstream
std::ofstream ifs("filename", std::ios::in);
DoSomethingWithStream(ifs);
ifs.close();

DoSomethingWithStream(std::cout);
}

Aug 15 '07 #2

P: n/a
On Aug 15, 7:31 am, masood.iq...@lycos.com wrote:
In the stdio library, supported by C, we can set a file pointer to
stdin or stdout ot stderr (e.g. FILE* fp = stdin;). Can we do
something similar with ifstream and ofstream in C++? i.e. can we set
the ifstream to stdin and the ofstream to stdout or stderr? If the
answer is yes, please provide a code snippet.

Thanks,
Masood

std::ofstream file("sil.txt",ios::out);

std::cout.rdbuf(file.rdbuf());

std::cout<<"this goes to the file"<<std::endl;

Aug 15 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.