Is there a common C library for reading name / value pairs from a file?

My program reads a text file containing various lines of text for the settings file. Some of the lines can become very large. Currently, the buffer size is 4096 characters. Perhaps some lines may exceed this, whether it be maliciousness or due to various factors operating within the program.

The current routines were quite tedious to write, and now I want to expand the possible contents of the file, which will require more of this tedious repeating code. (This is for a settings type file consisting of name value pairs and a random section header. Some numerical values ​​need to be read as strings due to multiple precision).

The main thing I want is to read an arbitrary string of length without buffer overflow. I just discovered that getline can do this for me, but is there a library in heaven that will just do all this tediousness for me?

change

I don’t want me to put the = sign between the name and values, the empty space should be sufficient as a separator.

By prevalence, I mean that the library should be available in standard packages of popular Linux distributions.

I know libconfig , but for my requirements it seems like a complete kink.

+6
c linux file-io settings
source share
3 answers

My suggestion is DIY, as it is pretty easy.

  • Read each line
  • count characters before your separator and after your separator
  • allocate buffers
  • and read name value pairs with sscanf

    as:

    sscanf(line, "%[^:]: %[^\n]", key, value);

You will be safe as you sccanf characters before sccanf .

+1
source share

Look libini sounds right. It is quite old and not quite going through crazy development, but if it already works for your problem, it should be fine.

A more modern library with a bunch of other glib benefits, it has an API key-value-parser .

+4
source share

I have implemented the updated fork libini in CCAN . It also contains a very useful dictionary implementation, as well as some simple hashing algorithms. Rusty put it on a repo, so I think I did a pretty good job of updating and fixing a few minor bugs.

The latest version of the library can be found if you break through this tree , it contains basic marker support, as well as basic transaction support (useful for re-reading configuration files and returning if there is a parsing error). It also contains a much more updated set of unit tests.

I do not actively support fork anymore, since the original author of libini was activated again, however the module is supported in CCAN.

+1
source share

All Articles