ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Hi i need to fast write a programme that reads parameters from a file (I think this is called file parser)
The conf file has the following syntax (like all the conf file)
parameter1=value1
parameter2=value2
I have thought many ways for doing this.
1)Use <string.h> for searching for a given paramater
-Drawbacks: I think that string.h dont provide every needed function so i need to implement new based on the allready defined... This perhaps needs lot of time and debugginf effort
2)Use other string libraries. Searching to the internet i have found the following http://bstring.sourceforge.net/
-Advantages: I can use better function for reading the file
Depending on the language, you can probably get some free stuff that does exactly what you want. Even if not the exact language, the code could serve as a model.
I use "javascriptsource.com" amd "freevbcode.com" for this.
I don't know if this meets the actual requirements. And it isn't exactly a paragon of elegance or efficiency. But I hope it might be of some use to you:
Code:
/*
* parse: parse simple name/value pairs
*
* SAMPLE BUILD:
* cc -g -Wall -o parse parse.c
*
* SAMPLE OUTPUT:
* ./parse =>
* Initializing parameters to default values...
* Reading config file...
* Final values:
* item: cone, flavor: vanilla, size: large
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXLEN 80
#define CONFIG_FILE "sample.txt"
struct sample_parameters
{
char item[MAXLEN];
char flavor[MAXLEN];
char size[MAXLEN];
}
sample_parameters;
/*
* initialize data to default values
*/
void
init_parameters (struct sample_parameters * parms)
{
strncpy (parms->item, "cup", MAXLEN);
strncpy (parms->item, "chocolate", MAXLEN);
strncpy (parms->item, "small", MAXLEN);
}
/*
* trim: get rid of trailing and leading whitespace...
* ...including the annoying "\n" from fgets()
*/
char *
trim (char * s)
{
/* Initialize start, end pointers */
char *s1 = s, *s2 = &s[strlen (s) - 1];
/* Trim and delimit right side */
while ( (isspace (*s2)) && (s2 >= s1) )
s2--;
*(s2+1) = '\0';
/* Trim left side */
while ( (isspace (*s1)) && (s1 < s2) )
s1++;
/* Copy finished string */
strcpy (s, s1);
return s;
}
/*
* parse external parameters file
*
* NOTES:
* - There are millions of ways to do this, depending on your
* specific needs.
*
* - In general:
* a) The client will know which parameters it's expecting
* (hence the "struct", with a specific set of parameters).
* b) The client should NOT know any specifics about the
* configuration file itself (for example, the client
* shouldn't know or care about it's name, its location,
* its format ... or whether or not the "configuration
* file" is even a file ... or a database ... or something
* else entirely).
* c) The client should initialize the parameters to reasonable
* defaults
* d) The client is responsible for validating whether the
* pararmeters are complete, or correct.
*/
void
parse_config (struct sample_parameters * parms)
{
char *s, buff[256];
FILE *fp = fopen (CONFIG_FILE, "r");
if (fp == NULL)
{
return;
}
/* Read next line */
while ((s = fgets (buff, sizeof buff, fp)) != NULL)
{
/* Skip blank lines and comments */
if (buff[0] == '\n' || buff[0] == '#')
continue;
/* Parse name/value pair from line */
char name[MAXLEN], value[MAXLEN];
s = strtok (buff, "=");
if (s==NULL)
continue;
else
strncpy (name, s, MAXLEN);
s = strtok (NULL, "=");
if (s==NULL)
continue;
else
strncpy (value, s, MAXLEN);
trim (value);
/* Copy into correct entry in parameters struct */
if (strcmp(name, "item")==0)
strncpy (parms->item, value, MAXLEN);
else if (strcmp(name, "flavor")==0)
strncpy (parms->flavor, value, MAXLEN);
else if (strcmp(name, "size")==0)
strncpy (parms->size, value, MAXLEN);
else
printf ("WARNING: %s/%s: Unknown name/value pair!\n",
name, value);
}
/* Close file */
fclose (fp);
}
/*
* program main
*/
int
main (int argc, char *argv[])
{
struct sample_parameters parms;
printf ("Initializing parameters to default values...\n");
init_parameters (&parms);
printf ("Reading config file...\n");
parse_config (&parms);
printf ("Final values:\n");
printf (" item: %s, flavor: %s, size: %s\n",
parms.item, parms.flavor, parms.size);
return 0;
}
Here's a corresponing "sample.txt" config file:
Quote:
#
# Test file
#
item=cone
flavor=vanilla
size=large
Your .. PSM
PS:
I meant what I said about mailing you a copy of K&R, if you'd like!
paulsm4: Don't have a call to feof() as the while-condition, instead have the call to fgets() that's presently
in the body of the loop as the while-condition. fgets() will fail when it's at EOF and tries to read and the loop
will break. Your version will copy the last line twice. See http://www.eskimo.com/~scs/C-faq/q12.2.html for details.
1. Modified "trim()" so that it eliminated whitespace before and after the word (or words) parsed from the input buffer.
2. Added the Standard C header <ctype.h> for the macro "isspace()" in order to detect whitespace.
3. Modified 'parse_config()" to trim the name and value pairs individually
4. Modified "parse-config()" to check fgets() to determine EOF (instead of using "feof()").
I don't know if this meets the actual requirements. And it isn't exactly a paragon of elegance or efficiency. But I hope it might be of some use to you:
Code:
/*
* parse: parse simple name/value pairs
*
* SAMPLE BUILD:
* cc -g -Wall -o parse parse.c
*
* SAMPLE OUTPUT:
* ./parse =>
* Initializing parameters to default values...
* Reading config file...
* Final values:
* item: cone, flavor: vanilla, size: large
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXLEN 80
#define CONFIG_FILE "sample.txt"
struct sample_parameters
{
char item[MAXLEN];
char flavor[MAXLEN];
char size[MAXLEN];
}
sample_parameters;
/*
* initialize data to default values
*/
void
init_parameters (struct sample_parameters * parms)
{
strncpy (parms->item, "cup", MAXLEN);
strncpy (parms->item, "chocolate", MAXLEN);
strncpy (parms->item, "small", MAXLEN);
}
/*
* trim: get rid of trailing and leading whitespace...
* ...including the annoying "\n" from fgets()
*/
char *
trim (char * s)
{
/* Initialize start, end pointers */
char *s1 = s, *s2 = &s[strlen (s) - 1];
/* Trim and delimit right side */
while ( (isspace (*s2)) && (s2 >= s1) )
s2--;
*(s2+1) = '\0';
/* Trim left side */
while ( (isspace (*s1)) && (s1 < s2) )
s1++;
/* Copy finished string */
strcpy (s, s1);
return s;
}
/*
* parse external parameters file
*
* NOTES:
* - There are millions of ways to do this, depending on your
* specific needs.
*
* - In general:
* a) The client will know which parameters it's expecting
* (hence the "struct", with a specific set of parameters).
* b) The client should NOT know any specifics about the
* configuration file itself (for example, the client
* shouldn't know or care about it's name, its location,
* its format ... or whether or not the "configuration
* file" is even a file ... or a database ... or something
* else entirely).
* c) The client should initialize the parameters to reasonable
* defaults
* d) The client is responsible for validating whether the
* pararmeters are complete, or correct.
*/
void
parse_config (struct sample_parameters * parms)
{
char *s, buff[256];
FILE *fp = fopen (CONFIG_FILE, "r");
if (fp == NULL)
{
return;
}
/* Read next line */
while ((s = fgets (buff, sizeof buff, fp)) != NULL)
{
/* Skip blank lines and comments */
if (buff[0] == '\n' || buff[0] == '#')
continue;
/* Parse name/value pair from line */
char name[MAXLEN], value[MAXLEN];
s = strtok (buff, "=");
if (s==NULL)
continue;
else
strncpy (name, s, MAXLEN);
s = strtok (NULL, "=");
if (s==NULL)
continue;
else
strncpy (value, s, MAXLEN);
trim (value);
/* Copy into correct entry in parameters struct */
if (strcmp(name, "item")==0)
strncpy (parms->item, value, MAXLEN);
else if (strcmp(name, "flavor")==0)
strncpy (parms->flavor, value, MAXLEN);
else if (strcmp(name, "size")==0)
strncpy (parms->size, value, MAXLEN);
else
printf ("WARNING: %s/%s: Unknown name/value pair!\n",
name, value);
}
/* Close file */
fclose (fp);
}
/*
* program main
*/
int
main (int argc, char *argv[])
{
struct sample_parameters parms;
printf ("Initializing parameters to default values...\n");
init_parameters (&parms);
printf ("Reading config file...\n");
parse_config (&parms);
printf ("Final values:\n");
printf (" item: %s, flavor: %s, size: %s\n",
parms.item, parms.flavor, parms.size);
return 0;
}
Here's a corresponing "sample.txt" config file:
Your .. PSM
PS:
I meant what I said about mailing you a copy of K&R, if you'd like!
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.