PDA

View Full Version : parsing strings in c: what is the right way?




wala
Dec 26, 2006, 08:30 PM
What would be a normal way to, say, parse a string from a configuration file for a program written in C? Would it simply be a series of while loops, eg, in the case of getting past whitespace, something like:

while(*string && isblank(*string))
string++;

Or are there standard libraries and tools which should be used to parse strings besides functions like strtok()?



bronxbomber92
Dec 26, 2006, 10:03 PM
I would say these would provide the combination of functions (and good memory management) to do what you want (and more)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>

wala
Dec 26, 2006, 10:21 PM
I would say these would provide the combination of functions (and good memory management) to do what you want (and more)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
What is the current official recommendation regarding malloc.h? I haven't seen much code which uses that #include....

iMeowbot
Dec 26, 2006, 10:22 PM
It almost seems as though there as many "right" ways to do this as there are programs, everyone feels the need to reinvent this stuff. Once upon a time this kind of made sense, but there are good standardised alternatives today.

On the Mac, you can use property lists, all the hairy code is already written. On Windows, use the registry. On "plain" Unixy systems, there are lots of nice libraries around that will handle XML, LanMan-style .ini files, and many more (and those would be fine with the Mac and Windows too, if you want a single implementation).

gnasher729
Dec 27, 2006, 04:34 AM
What is the current official recommendation regarding malloc.h? I haven't seen much code which uses that #include....

That's not surprising, because malloc, calloc, realloc and free are included in stdlib.h.

edm
Dec 27, 2006, 10:07 AM
Seems like there would be a Regular Expressions library available in C that would handle all all your parsing needs.

darkwing
Dec 27, 2006, 10:20 AM
Seems like there would be a Regular Expressions library available in C that would handle all all your parsing needs.

I agree. Use regex!

On OSX, just type "man regex" at a terminal prompt

wala
Dec 27, 2006, 07:47 PM
How would I use regexec's substring matching feature? (I cannot seem to find understandable documentation for it)
Examples would be nice....