如果我的程序有两个命令行参数,那么
./program hey.txt hello
但我想接受像这样的第一个论点
./program hello < hey.txt
我怎么能这样做?
答案 0 :(得分: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 );
}
答案 1 :(得分:-4)
你可以使你的程序接受三个参数,可以通过判断第二个参数是什么来选择你的操作,就像这样
int main(int argc, const char *argv[])
{
if (argv[2] == "<") {
dosomethings;
}
return 0;
}
请注意:http://publications.gbdirect.co.uk/c_book/chapter10/arguments_to_main.html