Maxim Menshikov

Static analysis reseacher and startup founder


A library for parsing printf format Announcements

Once I needed to parse printf format string. Surprisingly, I haven’t found any decent library to do this. Most sources suggest using regular expressions, but I wanted a more elegant solution for my future projects.

Here it is: pure C library for parsing the format. Its usage is as simple as:

#include "fmt_parser.h"
#include "fmt_util.h"
#include <stdio.h>

int main()
{
    fmt_status  rc;
    fmt_spec    spec;
    const char *str = "Hello, %157$02ld test %*s world!";
    const char *tmp = str;

    do
    {
        fmt_spec_init(&spec);
        rc = fmt_read_one(&tmp, &spec);
        if (rc == FMT_EOK)
        {
            fmt_spec_print(&spec, stdout);
            printf("\n");
        }
    } while (fmt_read_is_ok(rc));

    return 0;
}

Additionally, it doesn’t allocate memory, so it is safe in that aspect.

Specifier API

If you use it from other languages, the specifier API might be handy for you as it provided some wrappers for string and specifier allocation (you should not need to know the compile-time size of structures then). This API can be disabled using -DENABLE_SPEC_API=OFF.

Custom char type

Some projects might use a custom char type. The library doesn’t support runtime change of char type as of now, but it provides an option to set up type in compile time. See -DCHAR_TYPE.

Future directions

The library doesn’t support custom specifiers. Moreover, it doesn’t support de-facto standard specifiers from Microsoft, Linux, etc. I will improve the library as I see the need for it (I will).

Contributions are always welcome! The MIT license allows reusing the library in other projects pretty freely.