PDA

View Full Version : input text file woes ...


LiquidG
01-14-2003, 10:11 PM
In short, here's my dillemma:

I have this C file I've been working on, file1.c, that has a bunch of global variables contained in it (amongst other things). I'm going to run this file on a system that does not have a compiler on it, so I will be statically compiling it on another machine and coping it over. Before the execution of the file1.c (on the compiler-less system), I want to be able to change the values of some of the global variables, so I thought the best way would be to read them from a *.txt file. Thing is, all the vars may not need changing, and the *.txt file should only contain the "updates" to only those global vars that need changing (from the defaults set in file1.c).

Any suggestions?? I'm at a complete and utter loss.

PrBacterio
01-15-2003, 02:28 AM
So, you need a configuration file for your application?

Why not simply do something like this (warning untested code ahead) to simply read config files of the form "VALUENAME=VALUE" ?
/** return 0 on success, -1 on unknown identifier */
int apply_config_value(const char *identifier, int value)
{
if(!stricmp(identifier, "MAXBUFFERALLOC"))
{
cfg_max_buffer_alloc = value;
return 0;
}
/* ... */
return -1;
}

const char *read_identifier(FILE *file)
{
static char the_identifier[IDENT_MAX_LENGTH];
/* fill in reading of identifier */
return the_identifier;
}

/** read an integer from the file;
* return -1 on syntax error, 0 = OK */
int read_value(FILE *file, int *the_value)
{
/* fill in reading of value */
}

void skip_whitespace(FILE *file) { /* ... */ }
void skip_to_end_of_line(FILE *file) { /* ... */ }

/** read settings from configuration file
* returns 0, if no config file found
* returns 1 otherwise
* returns -1 on config file syntax error */
int read_configuration_file(const char *config_file_name)
{
FILE *config_file;
int read_char;
config_file = fopen(config_file_name, "rt");
if(!config_file) return 0;
while(!feof(config_file))
{
skip_whitespace(config_file);
read_char = fgetc(config_file);
switch(read_char)
{
case '#': /* comment */
skip_to_end_of_line(config_file);
break;

case EOF:
case '\n': /* empty line */
break;

default:
if(read_char >= 'A' && read_char <= 'Z' || read_char >= 'a' && read_char <= 'z')
{
const char *identifier = read_identifier(config_file);
int value;
skip_whitespace(config_file);
read_char = fgetc(config_file);
if(read_char != '=' || read_value(config_file, &value))
{
fclose(config_file);
return -1;
}
if(apply_config_value(identifier, value))
{
fclose(config_file);
return -1;
}
skip_to_end_of_line(config_file);
break;
}
else
{
fclose(config_file);
return -1;
}
}
}
fclose(config_file);
return 1;
}