Trying to read values from a file into a structure...

Posted by Trom on Tue 29 Apr 2008 06:24 PM — 2 posts, 12,809 views.

#0
What i'm trying to do is simply read values to a structure. It seems though that when i try to use 'fread_string()', it

crashes in gdb pointing to this.


Program received signal SIGSEGV, Segmentation fault.
fread_string (fp=0x951ff4) at db.c:2971
2971        if ( ( *plast++ = c ) == '~' )


I did not modify fread_string, the entire start of the function looks like this:


char *fread_string( FILE *fp )
{
    char *plast;
    char c;

    plast = top_string + sizeof(char *);
    if ( plast > &string_space[MAX_STRING - MAX_STRING_LENGTH] )
    {
	bug( "Fread_string: MAX_STRING %d exceeded.", MAX_STRING );
	exit( 1 );
    }

    /*
     * Skip blanks.
     * Read first char.
     */
    do
    {
	c = getc( fp );
    }
    while ( isspace(c) );

    if ( ( *plast++ = c ) == '~' )
		return &str_empty[0];

    for ( ;; )
    {
        /*
         * Back off the char type lookup,
         *   it was too dirty for portability.
         *   -- Furey
         */

	switch ( *plast = getc(fp) ) // error here


I'm using the loop method to read in the values, so it reads the keyword then reads the value based on the specific

word that has been read. The following is the code that reads the files string.


if ( !str_cmp(word,"Name") ) {
	ql->name = str_dup(fread_string(fp));
	fMatch = TRUE;
}


Now finally this is what the file contains:


#QL
Name (null)~
Id   7
Setid 0
Gold 0
Qp   5
Xp   5
End

#End


The first line is read without problem but it crashes as soon as it has to read the string just after the "Name" field. The

fread_string crashes like this in gdb [with or without the tilde]. Ql variable is assigned perm allocated memory so its

fine, i've used it in other structures before successfully without warnings or errors. I've even tried to use fscanf but it

always segmentation faults no matter how its used:


if ( !str_cmp(word,"Name") ) {
	fscanf( fp, "%s", ql->name);
                //char *temp = "";
                //fscanf( fp, "%s", temp);
                //ql->name = temp;
                //ql->name = str_dup(temp);
	fMatch = TRUE;
}


I can't seem to get the values read at all, fread_string and fscanf are not working..

#1
Nevermind, i was able to figure out a solution. Using the fscanf() method, using a string that consisted of 'char string[MSL]' i was able to get it to work. The problem for fscanf() seemed to be that i was trying to use a 'char *string' type of approach.