code_junkie

Obtain a std::ostream either from std::cout or std::ofstream(file)

Nov 12th, 2011
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. std::ostream out = condition ? &std::cout : std::ofstream(filename);
  2.  
  3. int main(int argc, char *argv[])
  4. {
  5. std::ostream* fp; //1
  6. if (argc > 1)
  7. fp = new std::ofstream(argv[1]); //2
  8. else
  9. fp = &std::cout //3
  10.  
  11. *fp << "Hello world!" << std::endl; //4
  12. if (fp!=&std::cout)
  13. delete fp;
  14. }
  15.  
  16. std::streambuf * buf;
  17. std::ofstream of;
  18.  
  19. if(!condition) {
  20. of.open("file.txt");
  21. buf = of.rdbuf();
  22. } else {
  23. buf = std::cout.rdbuf();
  24. }
  25.  
  26. std::ostream out(buf);
  27.  
  28. std::ofstream file("file.txt");
  29. std::streambuf * old = std::cout.rdbuf(file.rdbuf());
  30. // do here output to std::cout
  31. std::cout.rdbuf(old); // restore
  32.  
  33. struct opiped {
  34. opiped(std::streambuf * buf, std::ostream & os)
  35. :os(os), old_buf(os.rdbuf(buf)) { }
  36. ~opiped() { os.rdbuf(old_buf); }
  37.  
  38. std::ostream& os;
  39. std::streambuf * old_buf;
  40. };
  41.  
  42. int main() {
  43. // or: std::filebuf of;
  44. // of.open("file.txt", std::ios_base::out);
  45. std::ofstream of("file.txt");
  46. {
  47. // or: opiped raii(&of, std::cout);
  48. opiped raii(of.rdbuf(), std::cout);
  49. std::cout << "going into file" << std::endl;
  50. }
  51. std::cout << "going on screen" << std::endl;
  52. }
  53.  
  54. void process(std::ostream &os);
  55.  
  56. int main(int argc, char *argv[]) {
  57. std::ostream* fp = &cout;
  58. std::ofstream fout;
  59. if (argc > 1) {
  60. fout.open(argv[1]);
  61. fp = &fout;
  62. }
  63. process(*fp);
  64. }
  65.  
  66. std::ofstream of;
  67. std::ostream& out = condition ? std::cout : of.open(filename);
Add Comment
Please, Sign In to add comment