0

我有这个 C 程序,它应该被赋予如下参数:

./program -i inputFile -o outputFile

这是我的相关代码部分

  while ((c = getopt(argc, argv, "i:o:")) != -1) {
            switch (c) {


                 case 'i':
                          inFile = strdup(optarg);
                 break;
                 case 'o':
                          outFile = strdup(optarg);
                 break;
                 default:

                          error_usage(argv[0]);

                      }
                }

这里还有 error_usage 函数:

void error_usage(char *prog)
      {
        fprintf(stderr, "Usage: %s  -i inputfile -o outputfile\n", prog);
        exit(1);
      }

我应该如何修改我的case语句,如果我运行我的程序如下: ./program 它给我以下错误? Usage: prog -i inputfile -o outputfile

4

2 回答 2

2

Before you call getopt, check argc

if ( argc == 1 )
{
  fprintf(stderr, "... ");
  return -1;
}
于 2013-09-23T05:09:20.357 回答
2

See inFile and outFile to NULL

Then after your getopts loop check to see if either is still NULL. If they are then print the usage message and exit

if (inFile == NULL || outFile == NULL)
    error_usage(argv[0]);
于 2013-09-23T05:09:21.963 回答