开发者

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

开发者 https://www.devze.com 2022-12-17 20:41 出处:网络
My program is reading a text file containing various lines of text for a settings file. Some of the lines could get very large. Currently the buffer size is 4096 chars. It is possible that some lines

My program is reading a text file containing various lines of text for a settings file. Some of the lines could get very large. Currently the buffer size is 4096 chars. It is possible that some lines could exceed this, whether through maliciousness or due to various factors operating within the program.

The current routines were rather tedious to write and now I want to expand the possible contents of the file which will require more of this tedious repetitive code. (This is for a settings type file, consisting of name value pairs and the occasional 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 length line without buffer overflow. I've just discovered getline can do this for me, but, is there for heavens sake a library that will just do the whole lot of this tediousness for me?

edit:

I don't wish to be forced to place an = sign between the name and values, a blank space should suffice as separator.

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

I'm aware of libconfig 开发者_StackOverflow中文版but it seems complete overkill for my requirements.


Look into libini, sounds about right. It is quite old and not exactly undergoing frantic development, but if it already works for your problem, that should be fine.

A more up to date library, with a bunch of other benefits, is glib, it has a key-value-parser API.


My suggestion is, DIY, since it's quite easy.

  • Read each line

  • count chars until your separator and after your separator

  • allocate buffers

  • and read name value pairs with sscanf

    like:

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

You will be safe since you counted chars before sccanf.


I contributed an updated fork of libini at CCAN. It also contains a very useful dictionary implementation as well as some simple hashing algorithms. Rusty put it in the repo, so I guess I did a reasonably good job of bringing it up to date and fixing the few minor bugs.

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

I don't actively maintain the fork any more, as the original author of libini became active again, however the module is maintained in CCAN.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号