Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- std::ostream out = condition ? &std::cout : std::ofstream(filename);
- int main(int argc, char *argv[])
- {
- std::ostream* fp; //1
- if (argc > 1)
- fp = new std::ofstream(argv[1]); //2
- else
- fp = &std::cout //3
- *fp << "Hello world!" << std::endl; //4
- if (fp!=&std::cout)
- delete fp;
- }
- std::streambuf * buf;
- std::ofstream of;
- if(!condition) {
- of.open("file.txt");
- buf = of.rdbuf();
- } else {
- buf = std::cout.rdbuf();
- }
- std::ostream out(buf);
- std::ofstream file("file.txt");
- std::streambuf * old = std::cout.rdbuf(file.rdbuf());
- // do here output to std::cout
- std::cout.rdbuf(old); // restore
- struct opiped {
- opiped(std::streambuf * buf, std::ostream & os)
- :os(os), old_buf(os.rdbuf(buf)) { }
- ~opiped() { os.rdbuf(old_buf); }
- std::ostream& os;
- std::streambuf * old_buf;
- };
- int main() {
- // or: std::filebuf of;
- // of.open("file.txt", std::ios_base::out);
- std::ofstream of("file.txt");
- {
- // or: opiped raii(&of, std::cout);
- opiped raii(of.rdbuf(), std::cout);
- std::cout << "going into file" << std::endl;
- }
- std::cout << "going on screen" << std::endl;
- }
- void process(std::ostream &os);
- int main(int argc, char *argv[]) {
- std::ostream* fp = &cout;
- std::ofstream fout;
- if (argc > 1) {
- fout.open(argv[1]);
- fp = &fout;
- }
- process(*fp);
- }
- std::ofstream of;
- std::ostream& out = condition ? std::cout : of.open(filename);
Add Comment
Please, Sign In to add comment