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

M

masood.iqbal

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
 
O

Ondra Holub

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::eek:stream& os)
{
os << "Do something here\n";
}

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

DoSomethingWithStream(std::cout);
}
 
H

hurcan solter

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::eek:fstream file("sil.txt",ios::eek:ut);

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

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top