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

查看:35
本文介绍了从命令行将参数传递给 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)执行某些代码部分.

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天全站免登陆