In C++ programs, it's sometimes important to know whether the output is being displayed directly on the terminal or redirected to a file or pipe. This can help adjust formatting, enable or disable color output, or choose different logging behavior. For instance, progress bars or interactive prompts make sense only when writing to a terminal. This tutorial demonstrates how to check if standard output is terminal or redirected using C++.
C++ itself doesn't provide a direct way to detect this, but most operating systems offer a simple API to check. The key idea is to query if the standard output file descriptor points to a terminal device.
Different platforms provide different APIs:
- Unix systems (Linux, macOS, etc.) use the
isattyfunction. - Windows provides
_isattyfunction.
We can write a cross-platform check using conditional compilation:
#include <iostream>
#ifdef _WIN32
#include <io.h>
#define isatty _isatty
#define fileno _fileno
#else
#include <unistd.h>
#endif
int main() {
if (isatty(fileno(stdout))) {
std::cout << "stdout is terminal" << std::endl;
} else {
std::cout << "stdout is redirected" << std::endl;;
}
return 0;
}
Run normally in a terminal:
./test
Output:
stdout is terminal
Redirect output to a file:
./test > test.txt
File content:
stdout is redirected
Pipe output to another command:
./test | grep redirected
This will also detect redirection.
Leave a Comment
Cancel reply