Parsing string based on initial format

Posted by Kayla on Stack Overflow See other posts from Stack Overflow or by Kayla
Published on 2011-11-20T01:00:31Z Indexed on 2011/11/20 1:50 UTC
Read the original article Hit count: 114

Filed under:
|
|

I'm trying to parse a set of lines and extract certain parts of the string based on an initial format (reading a configuration file).

A little more explanation: the format can contain up to 4 parts to be formatted. This case, %S will skip the part, %a-%c will extract the part and will be treated as a string, %d as int.

What I am trying to do now is to come up with some clever way to parse it. So far I came up with the following prototype. However, my pointer arithmetic still needs some work to skip/extract the parts.

Ultimately each part will be stored on an array of structs. Such as:

struct st_temp
{
   char *parta;
   char *partb;
   char *partc;
   char *partd;
};
...

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

#define DIM(x) (sizeof(x)/sizeof(*(x)))

void process (const char *fmt, const char *line) {
   char c;
   const char *src = fmt;
   while ((c = *src++) != '\0')
   {   
      if (c == 'S');      // skip part
      else if (c == 'a'); // extract %a
      else if (c == 'b'); // extract %b
      else if (c == 'c'); // extract %c
      else if (c == 'd'); // extract %d (int)
      else { 
         printf("Unknown format\n");
         exit(1);
      }   
   }
}

static const char *input[] = {
   "bar 200.1 / / (zaz) - \"bon 10\"",
   "foo 100.1 / / (baz) - \"apt 20\"",
};

int main (void) {
   const char *fmt = "%S %a / / (%b) - \"%c %d\"";
   size_t i;
   for(i = 0; i < DIM (input); i++) 
   {
      process (fmt, input[i]);
   }   
   return (0);
}

© Stack Overflow or respective owner

Related posts about c

    Related posts about string