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)
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)
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).