Home > OS >  C program that only performs when there's an input redirection
C program that only performs when there's an input redirection

Time:09-22

I'm a C newbie and I need some help. So this is the problem I'm having with the terminal. Let's say I'm inputting a text file.

./Terminal < someFile.txt

How do I get my program to only perform a duty when a file has been input, else do another task?

int main() {
     //If user input is a file, do something
     if()
          //do something
     else
          //do something else
            
}

Sorry if I'm not formulating my question correctly, beginner programmer here.

CodePudding user response:

You can check if a program's stdin is connected to a terminal using isatty(0).

CodePudding user response:

It is standard for linux processes to read standard input, and write to standard output, unless given arguments to tell them to do otherwise. This enables pipelines, which are powerful.

If you want to know whether a file has been piped or redirected in, that will be a challenge. I recommend instead to use command-line arguments to allow the user to tell you which operation they want performed.

The getopt function is very helpful for this purpose.

  • Related