I am writing a program that takes several parameters on the command line and a filename as the last parameter. If the filename is a single dash - `-' I want my program to read from stdin. Otherwise, I want to read from specified file. I want this program to be portable.
However, this doesn't work with getopt:
Code:
while ((c = getopt (argc, argv, "ab-:")) != -1)
switch (c)
{
case 'a':
aflag = 1;
break;
case 'b':
bflag = 1;
break;
case '-':
cvalue = optarg;
printf("%s\n", cvalue);
$ ./main -"stuff"
Unknown option `-s'.
$ ./main - "stuff"
No output in second case. I came up with this:
Code:
while ((c = getopt (argc, argv, "ab-:")) != -1)
switch (c)
{
case 'a':
aflag = 1;
break;
case 'b':
bflag = 1;
break;
}
[...]
printf("last is: %s\n", argv[argc - 1]);
/* after getopt loop is finished, I will use strcmp to check if last argument is `-' and read from stdin, or if it's not and read from file */
Is this a good idea?