C - 检查 main 的参数

C - Check the arguments of the main

我需要检查主函数的参数。您可以 运行 带有 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

您没有在 main 中正确打印 FILEIN 的元素:

for(int i = 0; i < index; i++)
    printf("%s\n", FILEIN);

您正在将 FILEIN,这是一个 char * 的数组传递给 %s 格式说明符,它需要一个 char *。你忘了索引这个数组:

for(int i = 0; i < index; i++)
    printf("%s\n", FILEIN[i]);

关于读取的输入与输出不匹配,这是罪魁祸首:

char *FILEIN[];

这样的定义作为局部变量或全局变量(仅作为函数的参数)无效,因为未指定数组的大小。 gcc 会将其视为具有 1 个元素的数组,尽管这是编译器扩展。结果是您注销了数组的末尾,调用 undefined behavior.

你需要给这个数组一个固定的大小,例如:

char *FILEIN[100];

然后你需要确保你写的元素不超过(在本例中)100 个。