2014-09-27 39 views
0

If I have two command line arguments to my program like soc - How do you accept a command line argument via redirection

./program hey.txt hello 

but I wanted to accept the first argument like this

./program hello < hey.txt 

How would I be able to do that?

+0

The '<' and 'hey.txt' won't be seen by the program on Unix; the shell will interpret them as 'redirect standard input so it comes from the file 'hey.txt''. It is not at all clear, therefore, what you are after. At one level, there's nothing to do: if given one argument, the program can read from standard input. If you're trying to do something else, you'll need to explain it. – 2014-09-27 01:29:17

回答

-4

你可以使你的程序接受三個參數,可以通過判斷第二個參數是什麼來選擇你的操作,就像這樣

int main(int argc, const char *argv[]) 
{ 
    if (argv[2] == "<") { 
     dosomethings; 
    } 
    return 0; 
} 

note: http://publications.gbdirect.co.uk/c_book/chapter10/arguments_to_main.html

+0

I'm not sure what the ideographs say, but the code isn't accurate; either 'hey.txt' (two argument invocation) or 'hello' (one argument invocation) is found in 'argv[1]'. – 2014-09-27 01:26:50

+0

As noted by Johnathan Leffler, in a comment to the question, the shell will swallow the "< hey.txt" as a redirection and the program will never see it. – DoxyLover 2014-09-27 04:30:24

+0

@Jonathan Leffler "你可以使你的程序接受三個參數,可以通過判斷第二個參數是什麼來選擇你的操作,就像這樣" --> "You can make your program accepts three parameters, you can determine what the second parameter is to choose your operation, like this." – chux 2014-09-27 05:19:00

1
main(int argc, const char* argv[]) 
{ 
    FILE* inputFile = NULL; 
    if (argc == 3) 
    { 
     // I have 2 arguments. The first is a file name, the second is my other argument. 
     inputFile = fopen(argv[1], "r"); 
    } else if (argc == 2) { 
     // i have one argument so the input will come from stdin. 
     inputFile = stdin; 
    } 

    // now read the file somehow.... like with fread. 
    fread(inputFile); 
} 
相關問題