使用命令行参数时出现分段错误

Segmentation fault when using command line arguments

我正在尝试通过命令行参数获取输入和输出文件名。我只是在使用 getopt(告诉我是否有更好的方法)并且我得到了 segmentation fault

我确定分段错误是由输入文件的名称引起的。当我从命令行获取输入文件的名称时,出现了一些问题。

这是我的代码:

int main (int argc, char **argv) {

    char const *inFile = NULL; //I think the error is here
                               //an inFile that doesn't exist
                               //would cause a segmentation fault
    char const *outFile = "outfile.txt";
    double val;
    int xFlg= 0;
    int c;
    char *rm; //I need this for strtod, but I can use atoi instead

    while ( (c = getopt (argc, argv, "xo")) != -1 ) {
        switch (c) {
            case 'x':
                val = strtod(optarg, &rm);
                xFlg = 1;
                break;
            case 'o':
                outFile = optarg;
                break;
            default:
                help(); //void function that prints help
                return EXIT_FAILURE;
        }
        rm=NULL;
    }
    inFile = *(argv + optind);

    fread code
    .
    .
    .
    call function
    .
    .
    .
    fwrite code
}

我确信我的 freads 和 fwrites 没有问题,因为如果我使用 scanf 获取 inFile 和 outFile 的名称,一切都会完美无缺,而且我不会遇到分段错误。

我正在使用 xflg 的值来决定是否 运行 我的函数。 val 是我的函数采用的值。

这是我的函数:

void xFunc (input1, input2, val, xFlg) {
    if (xFlg == 1) {
        function code
        .
        .
        .
    } else {
    return; //don't run the function if the user doesn't type -x
            //into command line.
            //I don't know if this is the proper way to do this.
    }
}

这就是我想要实现的:

./运行 -x 3.14 -o outputfilename.txt inputfilename.txt

编辑:

如果我执行以下操作来获取输入文件名,则不会发生分段错误:

char inFile[100];
printf("Name of input file: \n");
scanf("%99s",somestring);

问题有两个:

char const *inFile = NULL;
......
inFile = *(argv + optind);

一旦你初始化了一个const char*,你就不能再给它赋值了。因此,要解决此问题,您可以尝试以下方法之一:

.....
 char const * inFile = *(argv + optind);
.....

如果在初始化之前不需要 inFile 指针,这应该没问题。

char inFile[20]; //whatever size you need
......
strcpy(inFile, *(argv + optind));

如果需要,您可以通过这种方式更改文件指针