LinuxQuestions.org
Review your favorite Linux distribution.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices

Reply
 
Search this Thread
Old 09-10-2005, 06:55 PM   #1
alaios
Senior Member
 
Registered: Jan 2003
Location: Aachen
Distribution: Opensuse 11.2 (nice and steady)
Posts: 2,133

Rep: Reputation: 45
Read parameters from config file (file parser?)


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

3)Havent thought anything else :P

So what do u suggest me to do?
 
Old 09-10-2005, 08:05 PM   #2
AnanthaP
Member
 
Registered: Jul 2004
Location: Chennai, India
Distribution: UBUNTU 5.10 since Jul-18,2006 on Intel 820 DC
Posts: 637

Rep: Reputation: 140Reputation: 140
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.

End.
 
Old 09-10-2005, 08:56 PM   #3
paulsm4
Guru
 
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,863
Blog Entries: 1

Rep: Reputation: Disabled
Hi -

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!

Last edited by paulsm4; 09-12-2005 at 12:35 AM.
 
Old 09-11-2005, 03:49 AM   #4
alaios
Senior Member
 
Registered: Jan 2003
Location: Aachen
Distribution: Opensuse 11.2 (nice and steady)
Posts: 2,133

Original Poster
Rep: Reputation: 45
thx but still doesnt remove space
for example param1= value1
will print: value1
 
Old 09-11-2005, 04:04 AM   #5
Hivemind
Member
 
Registered: Sep 2004
Posts: 273

Rep: Reputation: 30
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.
 
Old 09-11-2005, 10:39 AM   #6
paulsm4
Guru
 
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,863
Blog Entries: 1

Rep: Reputation: Disabled
Alaios - sounds like you want to enhance "trim()"!

Hivemind - you're correct. One solution (not the only solution, of course) is as you suggested:
Code:
  char *s, buff[MAXLEN];
  ...
  while ((s = fgets (buff, sizeof buff, fp)) {
    /* Skip blank lines and comments */
   if (buff[0] == '\n' || buff[0] == '#') {
    ..
 
Old 09-12-2005, 12:39 AM   #7
paulsm4
Guru
 
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,863
Blog Entries: 1

Rep: Reputation: Disabled
I modified the original program as follows:

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()").

The modified program is shown above.
 
Old 07-09-2012, 11:00 AM   #8
gcclinux
Member
 
Registered: Oct 2004
Location: London, UK
Distribution: Suse 12.1
Posts: 79

Rep: Reputation: 15
Quote:
Originally Posted by paulsm4 View Post
Hi -

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!
Brilliant, this is exactly what I wanted.
 
Old 07-09-2012, 11:29 AM   #9
gnashley
Amigo developer
 
Registered: Dec 2003
Location: Germany
Distribution: Slackware
Posts: 4,766

Rep: Reputation: 475Reputation: 475Reputation: 475Reputation: 475Reputation: 475
Brilliant. You resurrected a 7-year-old thread...
 
1 members found this post helpful.
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
read parameters from a file (c language) alaios Programming 7 08-20-2005 08:57 AM
anyone knows a config file parser (Linux/c/c++) Thinking Programming 2 07-28-2005 07:55 AM
read options from config file biiiep Programming 4 05-05-2005 03:30 AM
generic parser to read/write linux config files amitchandel Linux - Software 1 06-14-2004 04:00 PM
Unable to read config file............ FXRS Linux - Software 7 07-03-2003 08:36 AM


All times are GMT -5. The time now is 02:17 AM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration