【发布时间】:2018-10-20 16:28:23
【问题描述】:
我需要检查主函数的参数。您可以使用 2 个选项 -a 和 --b value 运行主程序,但有一些选项,您需要输入文件 (1,2...N) 和输出文件。
例如:./main -a --b 2 input1 input2 output
但选项可以在任何地方...
例如:./main input1 -a input2 input3 input4 output --b 1
运行程序所需的最低限度是输入和输出。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int NB = 1;
int FLAGA = 0;
const char *FILEOUT;
char *FILEIN[];
int args_check(int argc, char const **argv) {
int index = 0;
if(argc < 3){
printf("Not enough args.\n");
return -1;
}
for(int i = 1; i < argc; i++) {
if(strcmp(argv[i], "-a") == 0) {
FLAGA = 1;
}
else if(strcmp(argv[i],"--b") == 0) {
i++;
NB = atoi(argv[i]);
}
else {
FILEIN[index] = argv[i];
index++;
}
}
FILEOUT = FILEIN[index - 1];
printf("Input(s) :");
for(int i = 0; i < index - 1; i++)
printf(" %s", FILEIN[i]);
printf("\n");
printf("Output : %s\n", FILEOUT);
return index - 1;
}
int main(int argc, char const *argv[]) {
int index = args_check(argc, argv);
if(index < 0)
return 1;
for(int i = 0; i < index; i++)
printf("%s\n", FILEIN[i]);
return 0;
}
./main -a --b 1 test1 test2 test3 out,在我的终端上,我看到了
Input(s) : test1 out test3
Output : out
test1
out
test3
为什么我没有收到test1 test2 test3?
【问题讨论】:
-
为什么要重新发明轮子?在 Unix/Linux 系统上运行的函数
getopt会为您处理所有这些。如果您正在使用 Windows 系统,请查找XGetOpt