gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:15:01 29 4
gpt4 key购买 nike

我试图通过命令行参数获取输入和输出文件名。我正在使用 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.
}
}

这是我想要实现的:

./run -x 3.14 -o 输出文件名.txt 输入文件名.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));

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

关于c - 使用命令行参数时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36286979/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com