c - 从命令行将参数传递给 C 程序

所以我在 Linux 中,我想让一个程序在你从命令行执行它时接受参数。

例如,

./myprogram 42 -b -s

然后程序会将数字 42 存储为 int 并根据 -b 或 -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;
 }

https://stackoverflow.com/questions/498320/

相关文章:

linux - 如何在 Linux Shell 脚本中检查组是否存在并添加是否不存在

bash - 即使文件存在且不为空,也总是给出 false

linux - 向 unix shell 变量添加换行符

c - 在 C 中检测 64 位编译

linux - 如何在 Linux 上安装 Node 二进制分发文件

regex - 你如何用 sed "debug"一个正则表达式?

linux - 一个 C hello world 的汇编输出的每一行是什么意思?

python - 如何在python中检索进程开始时间(或正常运行时间)

linux - PHP CURL 启用 Linux

linux - 试运行 cron 条目