【发布时间】:2018-04-17 20:32:09
【问题描述】:
我创建了一个函数,它搜索文件的每一行并尝试将参数par_string 与文件中的字符串匹配。我有适用于双精度和整数的函数变体,但我似乎无法修改函数以从文件中读取字符串。
目前我正在使用sscanf() 读取一行,我目前的工作是使用strcpy() 将文件中的字符串复制到函数参数中定义的字符串参数parameter。然而,一旦我到达strcpy(),我的函数就会出现段错误,我不太明白为什么。
我希望能够在我的主函数中将函数调用为read_string("FILENAME", filename);,以便能够将参数传递给函数并将文件名返回给变量filename。我尝试使用
filename
char filename[MAXLINE]
和
char *filename = malloc(sizeof(*filename) * MAXLINE);
但两者都有同样的问题。
下面是我写的函数。有什么明显的我遗漏了,还是有更好的方法来做到这一点?
谢谢!
int
read_string(char par_string[], char *parameter)
{
char line[MAX_LINE], ini_par_name[MAX_LINE], par_separator[MAX_LINE];
char par_value[MAX_LINE];
FILE *par_file;
if ((par_file = fopen(INI_FILE, "r")) == NULL)
{
printf("Cannot open parameter file 'plane.ini'.\n");
exit(-1);
}
int linenum = 0;
parameter = STRING_NO_PAR_CONST;
while(fgets(line, MAX_LINE, par_file) != NULL)
{
linenum++;
/*
* If the line is a comment, skip that line. Note: There is a bug here
* which will cause the script to crash if there is a blank line.
*/
if (line[0] == '#' || line[0] == ' ')
{
continue;
}
/*
* Check a normal line is in the correct format
*/
if (sscanf(line, "%s %s %s", ini_par_name, par_separator, par_value) \
!= 3)
{
printf("Syntax error, line %d for parameter %s\n", linenum,
par_string);
exit(-1);
}
/*
* Use strcmp to compare the difference between two strings. If it's
* the same parameter, then strcmp will return 0.
*/
if (strcmp(par_string, ini_par_name) == 0)
{
strcpy(parameter, par_value);
}
}
/*
* If parameter wasn't updated, the parameter was not found. Return an
* error.
*/
if (parameter == STRING_NO_PAR_CONST)
{
printf("Parameter %s could not be found.\nExiting simulation.\n",
par_string);
exit(-1);
}
if (fclose(par_file) != 0)
{
printf("File could not be closed.\n");
exit(-1);
}
return 0;
}
【问题讨论】: