How to read input file with argv and redirect from input file

My program should accept three kinds of input commands below:

./Myprogram input.txt
./Myprogram < input.txt
./Myprogram

I am thinking of using argcto check the number of arguments to resolve the first two situations (since redirection is not considered an argument). But then I got stuck in the latter case, which is just waiting for user input.

I am wondering if there is a way to find out if redirection is present in the shell command?

For a more complex scenario, such as a combination of forwarding and argv forms (see below). Is there a way to do this or is it just a bad design for accepting custom commands?

./Myprogram input1.txt input2.txt input3.txt
./Myprogram input1.txt < input2.txt input3.txt
./Myprogram

Any help would be greatly appreciated!

Zen

+3
source share
5

. , :

./Myprogram input.txt
./Myprogram < input.txt
./Myprogram

. :

./Myprogram input1.txt input2.txt input3.txt
./Myprogram input1.txt < input2.txt input3.txt
./Myprogram

:

./Myprogram input1.txt input3.txt < input2.txt

:

./Myprogram input1.txt input3.txt

(, ).

, stdin , , "-" , " stdin ". "-", .

+6

:

if (there are no arguments left after parsing options)
    call_function(stdin);
else
{
    foreach remaining argument
    {
        FILE *fp;
        if (strcmp(argument, "-") == 0)
            call_function(stdin);
        else if ((fp = fopen(argument, "r")) == 0)
            ...error handling...
        else
        {
            call_function(fp);
            fclose(fp);
        }
    }
}

'call_function()', . ('call_function()') - , - . ; .

"" -, .

, . , UNIX, . . , , , , .

+4

@R.. .

№3, # 2, , isatty ( , isatty(0)), , .

C, !

+1

, , ?

. :

./Myprogram < input.txt
./Myprogram

.
shell, input.txt stdin , .

0

, select() stdin. , ( , - - stdin, ). , , , .

Alternatively, you can use isatty () on stdin to find out if it is tty or not. This is what most programs will do to find out if they are interactive or not, and probably better in your case.

Now you may notice that a lock that is awaiting user input in the third case is what all standard tools do, and this is probably the behavior that most users expect from your program.

0
source

Source: https://habr.com/ru/post/1770232/


All Articles