Check if Standard Input is Terminal or Redirected using C++

Check if Standard Input is Terminal or Redirected using C++

In many C++ programs, knowing where the input is coming from can influence how the program behaves. Interactive tools, prompts, and text-based UIs usually assume that the user is typing directly into a terminal. But when input is redirected from a file or piped from another command, those interactive features often need to be disabled. This tutorial shows how to check if standard input is terminal or redirected using C++.

The C++ standard library doesn't provide a built-in mechanism to detect this, operating systems expose simple functions that let you check whether standard input is connected to a terminal device.

Platform-specific functions:

  • On Unix-like environments (Linux, macOS, etc.), the function to use is isatty.
  • On Windows, the equivalent is _isatty.

By combining these with conditional compilation, we can write a portable code:

#include <iostream>

#ifdef _WIN32
#include <io.h>
#define isatty _isatty
#define fileno _fileno
#else
#include <unistd.h>
#endif

int main() {
    if (isatty(fileno(stdin))) {
        std::cout << "stdin is terminal" << std::endl;
    } else {
        std::cout << "stdin is redirected" << std::endl;;
    }

    return 0;
}

Normal execution by passing parameter:

./test param

Output:

stdin is terminal

Redirecting input from a file:

./test < test.txt

Output:

stdin is redirected

Using a pipe as input:

echo "param" | ./test

This will also detect redirection.

Leave a Comment

Cancel reply

Your email address will not be published.