How to handle exceptions when we give no argument to a C executable program [duplicate]

心已入冬 提交于 2019-12-24 19:16:50

问题


I have this C program in which it should be given arguments like the following:

./program -i inputFile -o outputFile

and here's my related section of code

  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]);

                      }
                }

also here's the error_usage function:

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

How should I modify my case statement in a way that if I run my program like the following: ./program it gives me the following error? Usage: prog -i inputfile -o outputfile


回答1:


Before you call getopt, check argc

if ( argc == 1 )
{
  fprintf(stderr, "... ");
  return -1;
}



回答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]);


来源:https://stackoverflow.com/questions/18952077/how-to-handle-exceptions-when-we-give-no-argument-to-a-c-executable-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!