
looking for function to read config file
Quote:
> Looking for examples of functions to do things related to reading
> various runtime option settings from an ascii configuration file.
> Standard ANSI C only, not proprietary libraries. Any suggestions
> appreciated.
Hi "Karen Streib",
ANSI-C does not provide direct functions for this. You will have to do
All the reading and decoding yourself, using the functions "fopen()",
"fgets()" and "fclose()".
The rest is up to you and the requirements on and format of your
configuration file. You can define a simple file format without
special features and without much of format or error checking or
you can introduce things like sections, comments, defaults, various
predefined entry types, etc.
A very simple file format would be:
EntryName1=
EntryName2=
...
With the entry names starting at the first column and the entry being
everything between the '=' and the end of the line. A simple function
for reading a specific entry would be:
#define FILE_NAME "test.txt"
#define MAXTEXT 80
int ReadEntry( const char *entryName, char *entryText, int maxText )
{
int found = 0;
int length;
char text[MAXTEXT];
char *s;
FILE *fp = fopen( FILE_NAME, "r" );
if ( fp == 0 ) return -1;
text[0] = 0;
while ( !found )
{
s = fgets( text, MAXTEXT, fp );
if ( s == NULL ) break;
length = strlen( entryText );
if ( strncmp(entryName, text, length) == 0 && text[length] == '=' )
{
strncpy( entryText, text+length+1, maxText );
found = 1;
}
}
fclose( fp );
return found;
Quote:
}
The function will return -1, 0 or 1 and, if found, the entry text
including the terminating '\n' is returned (if it fits). I leave it to
the reader to make improvements.
Stephan
(self appointed member of the campaign against grumpiness in c.l.c)