当我们给C可执行程序没有参数时,如何处理异常 [英] How to handle exceptions when we give no argument to a C executable program

查看:127
本文介绍了当我们给C可执行程序没有参数时,如何处理异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



。/程序-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;
默认值:

error_usage(argv [0]);

}
}

这里也是error_usage函数: / p>

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

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

解决方案

inFile outFile 到NULL



然后您的getopts循环检查以查看是否仍为NULL。如果他们打印使用消息并退出

  if(inFile == NULL || outFile == NULL)
error_usage(argv [0]);


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

解决方案

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

这篇关于当我们给C可执行程序没有参数时,如何处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆