Discussion:
Setting a file stream to std[in/out/err]?
(too old to reply)
m***@lycos.com
2007-08-15 04:31:51 UTC
Permalink
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
Ondra Holub
2007-08-15 04:59:45 UTC
Permalink
Post by m***@lycos.com
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);
}
hurcan solter
2007-08-15 06:02:03 UTC
Permalink
Post by m***@lycos.com
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;

Loading...