Home >Backend Development >C++ >How Can I Distinguish Between Terminal and Pipe Input in C/C ?

How Can I Distinguish Between Terminal and Pipe Input in C/C ?

Susan Sarandon
Susan SarandonOriginal
2024-12-10 16:35:14174browse

How Can I Distinguish Between Terminal and Pipe Input in C/C  ?

Identifying Standard Input Type: Terminal vs. Pipe in C/C

In the Python interactive shell, executing "python" without arguments initiates the REPL interface. However, running "cat | python" via the terminal bypasses the interactive mode, demonstrating that Python detects stdin (standard input) as a pipe. How can a similar distinction be made in C/C or Qt?

Solution: Utilize isatty()

To detect whether standard input is connected to a terminal or a pipe in C/C , employ the function isatty():

#include <stdio.h>
#include <io.h>
...

if (isatty(fileno(stdin))) {
  printf("stdin is a terminal\n");
} else {
  printf("stdin is a file or a pipe\n");
}

On Windows platforms, the function names are prefixed with underscores:

if (_isatty(_fileno(stdin))) {
  printf("stdin is a terminal\n");
} else {
  printf("stdin is a file or a pipe\n");
}

The above is the detailed content of How Can I Distinguish Between Terminal and Pipe Input in C/C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn