我想像这样为 c 程序设置参数。
$./Program_name -a 100 -b 5 -c 30
我想在程序中使用这个值a
、b
、c
。
例如:
int count = a;
int number = b;
int limit_exec = c;
我不知道它是如何工作的。我在 Google 中找不到它...我想查看一些示例。
同时,我想设置默认值和值限制。
设置限制如下:值
a
只能是1到10000之间的数字。当我没有输入值时使用默认值 像这样:
$./program -a 100 -c 30 // then value 'b' should use default number.
我不知道如何设置默认值。像这样在c代码中设置默认值可以吗?
#define a 50 #define b 100 #define c 30
最佳答案
您可以使用getopt
来解析命令行输入。
请参阅 man
页面了解简要想法。
$ man 3 getopt
以下代码可根据您的要求运行。
代码:
#include <stdio.h>
#include <unistd.h> /* Definition of getopt */
#include <stdlib.h> /* Definition of atoi */
int main (int argc, char ** argv)
{
char option;
/* Default Values */
int count = 10, number = 20, limit = 30;
while (-1 != (option = getopt (argc, argv, "a:b:c:")))
{
switch (option)
{
case 'a':
count = atoi(optarg);
/* Check for limit */
if (count <= 0 || count > 1000)
{
printf("Usage <%s> [a] value, Range of value : 1-1000\n", argv[0]);
exit(EXIT_FAILURE);
}
break;
case 'b':
number = atoi(optarg);
break;
case 'c':
limit = atoi(optarg);
break;
default:
printf ("Usage: <%s> [a] value [b] value [c] value\n", argv[0]);
}
}
printf("\nCount:[%d]\tNumber:[%d]\tlimit:[%d]\n\n", count, number, limit);
return 0;
}
编译: gcc -o exe filename.c -Wall
执行:
$ ./exe /* Default values */
Count:[10] Number:[20] limit:[30]
$ ./exe -a 1 -b 2 -c 3
Count:[1] Number:[2] limit:[3]
$ ./exe -a 1 -c 3
Count:[1] Number:[20] limit:[3]
$ ./exe -a 9999 /* Same output for ./exe -a -1 */
Usage <./exe> [a] value, Range of Value : 1-1000
关于c - 当我在 Unix 下运行 C 程序时,如何将参数读取为选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26248308/