我创建了一个函数,它搜索文件的每一行,并尝试将参数par_string与文件中的字符串匹配。我有函数的变体,适用于双倍和整数,但我似乎无法修改函数以从文件中读取字符串。
目前,我正在使用sscanf()读取一行,当前的工作是使用strcpy()将文件中的字符串复制到函数参数中定义的字符串参数parameter。然而,当我到达strcpy()时,我的函数就是seg错误,我不太清楚原因。
我希望能够在主函数中以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;
}发布于 2018-04-17 20:37:17
这条线在干什么?
parameter = STRING_NO_PAR_CONST;如果将parameter指定为指向字符串文本(这可能是您的问题),则不能修改字符串文本的内容。
如果STRING_NO_PAR_CONST是'\0',那就是char,而不是string。只要parameter在调用read_string()之前正确地分配了一些内存,您就可以
parameter[0] = STRING_NO_PAR_CONST同样的,当你检查它是否有变化时
if (parameter[0] == STRING_NO_PAR_CONST)发布于 2018-04-17 20:41:01
几件事
strcpy被调用为以下-> strcpy(目标、源)。您正在使用参数作为目标。
也就是说,您分配的空间应该是所需字符串的最大大小。我不认为它应该等于给定文件中的最大行数(尽管我可能错了)。
https://stackoverflow.com/questions/49887014
复制相似问题