I have created a function which searches each line of a file and tries to match the parameter par_string
with a string in the file. I have variants of the function working for doubles and ints, but I can't seem to modify the function to read in strings from file.
Currently I am using sscanf()
to read in a line and my current effort is to use strcpy()
to copy the string in the file to the string parameter parameter
defined in the function argument. However, my function is seg faulting once I reach strcpy()
, and I can't quite figure out why.
I'm hoping to be able to call the function as read_string("FILENAME", filename);
in my main function to be able to pass in a parameter to the function and have the filename returned to the variable filename
. I've tried defining filename
using
char filename[MAXLINE]
and
char *filename = malloc(sizeof(*filename) * MAXLINE);
but both have the same problem.
Below is the function I've written. Is there anything obvious I'm missing or is there a better way to do this?
Thanks!
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;
}