I am rather new to c, and I am having a parsing problem.

What I am trying to accomplish:
I have a file filled with assignment statements such as:



I want to parse through the file and then do a check to see if the variables exist in my main program. If they do, then I will override the default value with the one from the config file, if not, then I will just ignore them.

I have an idea how to open the file, and I kind of know how to parse the lines at the =, but from there I am lost.

Here is my code so far:

#include <stdio.h>
#include <string.h>
int main(void){
	static const char filename[] = ".configfile";
	FILE *file = fopen(filename, "r");
	if (file){
		char line[BUFSIZ];
		int k = 0;
		while ( fgets(line, sizeof line, file) ){
			int i;
			char *token = line;
			for(i=0; *token; ++i){
				size_t len = strcspn(token, "=");
				#Oh man, now what? 
				#No idea what to do here!
				# :(
				token += len + 1;
                #set defaults
	return 0;

Thanks in advance!

7 Years
Discussion Span
Last Post by Narue

>do a check to see if the variables exist in my main program
Just how do you plan on doing that? Are you also parsing the code of the main program? If not, do try to remember that variable names are lost during compilation. The big problems is that variable names are not a queryable entity. You need a more abstract form of storage such that you can hold both a conceptual name as well as the paired value for that name. An associative array is ideal, but for shorter lists a simple array will work just as well:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define length(a) (sizeof (a) / sizeof *(a))

struct variable {
    char *name;
    int value;

static const char *ini[] = {

int main ( void )
    struct variable vars[] = {
    size_t i;

    for ( i = 0; i < length ( ini ); i++ ) {
        char temp[BUFSIZ];
        char *name;
        size_t j;

        /* Simulate reading from a stream */
        strcpy ( temp, ini[i] );

        if ( ( name = strtok ( temp, "=" ) ) == NULL )

        for ( j = 0; j < length ( vars ); j++ ) {
            if ( strcmp ( vars[j].name, name ) == 0 )

        if ( j != length ( vars ) ) {
                - Assuming there's another token
                - Assuming the next token is a valid int

                Example only. Don't do this in real code
            vars[j].value = atoi ( strtok ( NULL, "=" ) );

    for ( i = 0; i < length ( vars ); i++ )
        printf ( "%s = %d\n", vars[i].name, vars[i].value );

    return 0;
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.