[英]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.
}
}
这是我要实现的目标:
./run -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));
如果需要,可以通过这种方式更改文件指针
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.