Hi all:

Try to do some programming under Linux.
The programme I am writing is supposed to read all the char from a file via "command in line argument (i.e. agv)" and via redirection (i.e. read <FILE_NAME.

In my program, I have written:

FILE *stream;

stream = fopen(argv,"r");

if (stream==NULL) /*The file name is not in the command line argument*/


I am wondering what I should do now to check if there is a redirection stdin.


Many thanks

Dani AI

Generated

Good start — @Wuzhang’s question and ’s fallback to using standard input cover the common cases. A couple of additions will make the program behave predictably when run interactively, in a pipeline, or with file redirection.

To detect whether input is coming from a terminal (keyboard) or has been redirected/piped, test the terminal status of stdin instead of guessing from argc. On POSIX systems use isatty(fileno(stdin)): it returns non‑zero for an interactive terminal and zero for a pipe/file. Example:

#include <stdio.h>
#include <unistd.h>

if (!isatty(fileno(stdin))) {
    /* stdin is redirected or piped */
} else {
    /* interactive: consider prompting */
}

If you need more detail (regular file vs FIFO/pipe), call fstat(fileno(stdin), &st) and inspect S_ISREG(st.st_mode) or S_ISFIFO(st.st_mode). Support the common "-" filename convention to explicitly mean "read from stdin" so callers can do prog - or prog - < file. Only call fclose() on streams your code opened; avoid closing stdin unless you intentionally replaced it (or use freopen() to normalize input to stdin).

Platform notes and pitfalls: on Windows use _isatty(_fileno(stdin)) and remember to set binary mode (_setmode) for raw data. Always check fopen return values and report errno for troubleshooting. Finally, if isatty() shows an interactive terminal, avoid blocking reads with no prompt; if input is redirected, suppress prompts so the program works cleanly in scripts and pipelines.

Recommended Answers

All 2 Replies

If you wish, your program can assume that if there was nothing on the command line, redirection is being used. In that case, instead of using the fopen(), simply assign stdin to your stream:

FILE *stream;

if (argc < 2)
{
    stream = stdin;
}
else
{
    stream = fopen(argv[i],"r");
    if (stream==NULL) 
   ...
}

This allows your program to take a file
> prog

redirected file
>prog <

or from the keyboard
>prog

Thanks man. Really appreciate it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.