参数传递到C程序的命令行 [英] Pass arguments into C program from command line

查看:137
本文介绍了参数传递到C程序的命令行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在Linux和我想要当你在命令行中执行它的程序接受参数。

So I'm in Linux and I want to have a program accept arguments when you execute it from the command line.

例如,

./ myprogram 42 -b -s

于是该计划将这一数字42存储为一个int,并根据它得到什么参数,像-b或-s执行code的某些部分。

So then the program would store that number 42 as an int and execute certain parts of code depending on what arguments it gets like -b or -s.

推荐答案

您可以使用 getopt的

 #include <ctype.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>

 int
 main (int argc, char **argv)
 {
   int bflag = 0;
   int sflag = 0;
   int index;
   int c;

   opterr = 0;

   while ((c = getopt (argc, argv, "bs")) != -1)
     switch (c)
       {
       case 'b':
         bflag = 1;
         break;
       case 's':
         sflag = 1;
         break;
       case '?':
         if (isprint (optopt))
           fprintf (stderr, "Unknown option `-%c'.\n", optopt);
         else
           fprintf (stderr,
                    "Unknown option character `\\x%x'.\n",
                    optopt);
         return 1;
       default:
         abort ();
       }

   printf ("bflag = %d, sflag = %d\n", bflag, sflag);

   for (index = optind; index < argc; index++)
     printf ("Non-option argument %s\n", argv[index]);
   return 0;
 }

这篇关于参数传递到C程序的命令行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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