It is well known that there are three default I/O streams which are mapped to predefined objects in the standard library:
- 0:
std::istream std::cin - 1:
std::ostream std::cout - 2:
std::ostream std::cerrandstd::ostream std::clog
However, from within (e.g.) a bash script you can create additional streams (3,4,…).
So, can you create an extra output stream with the descriptor 3 and bind it to an std::ostream custom object? If so, how? std::ofstream doesn’t do the trick as it would create a file with the name “3” which is not what I want.
Edit: It doesn’t have to be portable. It suffices if it works on POSIX.
It is not possible if you need your program to be portable. The C++ 11 Standard does not specify a unified way of doing that.
However, you can define your own output stream buffer which overrides the
overflow()andxsputn()virtual functions and writes each character or sequence of characters to the stream with the specified descriptor using system-specific API.Something along these lines:
And this is how you would use it: