0

I am trying to read from STDOUT in C++ but every example I find implies using pipe and dup and I wonder if is there a way to avoid them. Let's say just:

cout << "Hello world" << endl;

/* ... */

read(STDOUT_FILENO, buffer, MAX_LEN)
DYZ
  • 55,249
  • 10
  • 64
  • 93
Leonardo Lanchas
  • 1,616
  • 1
  • 15
  • 37
  • 1
    Why would you want to read STDOUT? It is an output channel intended for writing. – DYZ Jan 16 '17 at 21:07
  • Possible duplicate of [C++: Redirecting STDOUT](http://stackoverflow.com/questions/4810516/c-redirecting-stdout) — Particularly [this answer](http://stackoverflow.com/a/6211644/1241334) to that question. – Jonny Henly Jan 16 '17 at 21:08
  • but - instead of `cout` - why not stream to a `ostringstream` for example? – Nim Jan 16 '17 at 21:11

1 Answers1

2

The simple answer is you can't read from STDOUT_FILENO. The call to read will always return EBADF because STDOUT_FILENO is not valid to read from. That is why people use pipe and dup.


If you're looking for a more C++ approach to what I think you want to do, check out the answer to: How to redirect cin and cout to files? If you replace std::cout's output buffer with something of your own creation, you can manipulate it however you want. Unfortunately, this will only capture output operations to std::cout and not things like direct calls to write(STDOUT_FILENO, ...), printf(...) and whatnot. It is also way more inconvenient (in my experience).

Community
  • 1
  • 1
Travis Gockel
  • 26,877
  • 14
  • 89
  • 116