r/cprogramming • • 24d ago

I just built a simple parser to retrieve configuration from a plain file - any suggestions?

I have just created a very simple parser to retrieve configuration settings from a plain text file (this parser is still in its early stages and will likely be developed further). I plan to use it to parse configurations for a simple custom code editor that I am currently building in C.

A quick side note:

you might be wondering why I didn’t use a standard configuration file format like .INI. I actually did try using .INI files at first, but parsing them requires an external library. I experimented with a library called inih by benhoyt with BSD license, it worked well, but since it’s an external dependency, I would have had to include the ini.c and ini.h file in my repository. This raised some questions for me: should I push those files which I didn’t write myself to GitHub? Or should I just credit the creator in my repository’s README file? To be honest, I felt a bit uncertain and concerned about the licensing implications.

Then, I remembered that the nano code editor uses a plain text file (.nanorc) for its configuration. That gave me the idea to try using a plain text file for my own configuration and to write a simple parser for it from scratch in C. This might sound silly, but this way I don’t have to worry about licenses (honestly, it’s mostly because I don’t really understand them anyway), and I get to learn how to build my own simple parser.

How my code works:

There are two files: .test_configand test.c

.test_config file content:

num tab_stop = 4
num fg_color = 39
num bg_color = 49

bind exit = ^Q
bind move_up = up_arrow
bind move_down = down_arrow
bind move_right = right_arrow
bind move_left = left_arrow

Data in the .test_config file is divided into three parts:

type configuration_name = configuration_value

Currently, there are two type: num for configurations with numeric values, and bind for configurations that act as keys (bindings).

test.c file content:

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

// data
typedef struct {
    // Appearance
    int tab_stop;
    int fg_color;
    int bg_color;

    // Keybinds
    char exit[64];
    char move_up[64];
    char move_down[64];
    char move_left[64];
    char move_right[64];
} configuration;


// func Declaration
int read_config(char *filename, configuration *config);


int main() {
    configuration config;
    read_config(".test_config", &config);
    printf("tab_stop = %d\n", config.tab_stop);
    printf("fg_color = %d\n", config.fg_color);
    printf("bg_color = %d\n", config.bg_color);
    printf("\n");
    printf("exit = %s\n", config.exit);
    printf("move_up = %s\n", config.move_up);
    printf("move_down = %s\n", config.move_down);
    printf("move_left = %s\n", config.move_left);
    printf("move_right = %s\n", config.move_right);

    return 0;
}


// func Definition
int read_config(char *filename, configuration *config) {
    FILE *fp = fopen(filename, "r");

    if (fp == NULL) {
        printf("unable to open file\n");
        return 1;
    }

    char buffer[100];
    while (fgets(buffer, sizeof(buffer), fp)) {
        if (strstr(buffer, "num") != NULL) {

            char num_config_name[64];
            int num_config_value = 0;

            sscanf(buffer, "num %s = %d", num_config_name, &num_config_value);
            if (strcmp(num_config_name, "tab_stop") == 0) {
                config->tab_stop = num_config_value;
            } else if (strcmp(num_config_name, "fg_color") == 0) {
                config->fg_color = num_config_value;
            } else if (strcmp(num_config_name, "bg_color") == 0) {
                config->bg_color = num_config_value;
            }

        } else if (strstr(buffer, "bind") != NULL) {

            char bind_config_name[64];
            char bind_config_value[64];

            sscanf(buffer, "bind %s = %s", bind_config_name,bind_config_value);
            if (strcmp(bind_config_name, "exit") == 0) {
                strcpy(config->exit, bind_config_value);
            } else if (strcmp(bind_config_name, "move_up") == 0) {
                strcpy(config->move_up, bind_config_value);
            } else if (strcmp(bind_config_name, "move_down") == 0) {
                strcpy(config->move_down, bind_config_value);
            } else if (strcmp(bind_config_name, "move_left") == 0) {
                strcpy(config->move_left, bind_config_value);
            } else if (strcmp(bind_config_name, "move_right") == 0) {
              strcpy(config->move_right, bind_config_value);
            }
        }
    }
    fclose(fp);

    return 0;
}

Inside, there is a function called read_config() which simply works by first checking the configuration type, then verifying if the configuration name matches; if it does, it stores the value into the corresponding struct element.

Output:

tab_stop = 4
fg_color = 39
bg_color = 49

exit = ^Q
move_up = up_arrow
move_down = down_arrow
move_left = left_arrow
move_right = right_arrow

The code works smoothly and produces the expected output, but I’m not entirely sure if the underlying logic is as efficient as it could be, could the logic be improved further, or is it already sufficient? Also, do you have any other suggestions regarding the approach I’ve chosen for handling configuration files in the simple code editor I’m building?

Apologies if any of the explanations are a bit complicated or difficult to understand.

2 Upvotes

6 comments sorted by

4

u/torsten_dev 24d ago

You can write an INI parser yourself. Perhaps with the help of a parser/lexer generator.

Of note .INI isn't all that standardized and it is also a plain text format. If you are going to reinvent the wheel the .INI format is a good place to do it.

3

u/ffd9k 24d ago
char buffer[100];
...
while (fgets(buffer, sizeof(buffer), fp)) {
...
char num_config_name[64];
...
sscanf(buffer, "num %s = %d", num_config_name, &num_config_value);

Looks like a buffer overrun if the file contains a line like "num long_word_with_more_than_63_chars....."

2

u/Dapper-Situation-864 19d ago

Nice start. A few things that haven't been mentioned yet:

1. strstr matches anywhere in the line. bind number_key = x contains "num", so it would go down the num branch. Check the prefix instead, or simpler, let sscanf split the line once and check its return value:

char type[16], name[64], value[64];
if (sscanf(buffer, "%15s %63s = %63s", type, name, value) != 3)
    continue; /* blank line, comment or malformed */

The width limits also fix the overflow ffd9k pointed out, and checking the return value stops a bad line from leaving garbage in name.

2. Replace the if/else chains with a table, so adding a setting is one line:

#include <stddef.h>

enum opt_type { NUM, BIND };
struct opt { const char *name; enum opt_type type; size_t off; };

static const struct opt opts[] = {
    { "tab_stop",   NUM,  offsetof(configuration, tab_stop) },
    { "fg_color",   NUM,  offsetof(configuration, fg_color) },
    { "bg_color",   NUM,  offsetof(configuration, bg_color) },
    { "exit",       BIND, offsetof(configuration, exit) },
    { "move_up",    BIND, offsetof(configuration, move_up) },
    /* ... */
};

Loop over opts, compare name, check that type matches, and write through (char *)config + o->off. Use strtol for numbers so you can reject tab_stop = abc, and snprintf(dst, 64, "%s", value) instead of strcpy.

3. Allow comments and report errors. Skip lines starting with #, and print the line number for unknown keys ("line 7: unknown option foo"). Users of your editor will thank you.

4. Set defaults before reading, so a missing file or missing key still gives a usable editor. A missing config file probably shouldn't be fatal.

Efficiency-wise it's already fine: a config file is read once at startup, so clarity and error handling matter far more than speed.

On licensing: inih's BSD license lets you keep ini.c/ini.h in your repo as long as the license text stays with them (e.g. in a third_party/inih/ folder). But writing your own is a great exercise, so no reason to stop.

1

u/SheikHunt 24d ago

I don't have anything to add regarding the specific syntax and semantics of your configuration format, as I am not good enough at grammars to help out with specifics.

What I do know about including external libraries is that there are generally two ways to do it: Vendoring, and shared libraries.

Shared libraries are weird and funky and generally they make you do work outside of the code for your program: no bueno for most cases.

Vendoring is exactly what you described: literally including some or all of the implementation of the external library in your repository as if it were any other file, with two catches that I can think of:

  1. respecting the licensing rules. You already said you had fears about that, and I can't be arsed to check the license for that specific parser, but generally, most libraries include their license in every single file, and simply copying and pasting said file (and in some license's cases, even modifying it) are allowed so long as you keep the license. But, yes, being cautious is better; ask when you don't know.
  2. Project structure. You probably don't want the external library's files to get mixed up with your own projects', but fixing that is as simple as putting the external libraries' files in a "thirdparty" or "external" directory or folder.

Beyond that, I'm not aware of any specifics that you'll have to be aware of. Good luck with the editor!

1

u/Humble-Captain3418 24d ago

Comment on the keybinds: USB HID uses 2×16 bit key codes across all devices. Translating the key names to integers would allow you to have the key combinations in a more machine readable format and much denser, to boot.

1

u/actguru 21d ago

You should probably initialize 'config', sanity check values, check for extra values and missing values, etc. Good Luck.