glib读写配置文件接口

源代码:

#include <stdio.h>
#include <glib.h>

int main()
{
    gchar *conf_file, *conf;
    GKeyFile *keyfile = NULL;
    GError *error = NULL;
    gchar **keys = NULL;
    gsize nkeys, i;

    /*创建对象*/
    keyfile = g_key_file_new();

    /*打开配置文件/root/.config/spicy/setting*/
    /*g_get_user_config_dir()   ====    /root/.config/*/
    conf_file = g_build_filename(g_get_user_config_dir(), "spicy", "settings", NULL);
    if (!g_key_file_load_from_file(keyfile, conf_file,
                                   G_KEY_FILE_KEEP_COMMENTS|G_KEY_FILE_KEEP_TRANSLATIONS, &error)) {
        g_clear_error(&error);
    }

    /*读取配置文件的general类别有几个小字段*/
    keys = g_key_file_get_keys(keyfile, "general", &nkeys, &error);
    g_print("%d\n", nkeys);

    for (i = 0; i < nkeys; ++i) {
        g_print("%s\n", keys[i]);
    }

    /*获取gt类别下的abc字段的string*/
    gchar *str = g_key_file_get_string(keyfile, "gt", "abc", &error);
    g_print("%s\n", str);
    g_free(str);

    /*获取ui类别下的toolbar字段的bool*/
    gboolean state = g_key_file_get_boolean(keyfile, "ui", "toolbar", &error);
    if (state)
        g_print("true\n");

    /*这边是写配置到keyfile中*/
    g_key_file_set_boolean(keyfile, "gt", "def", 0);
    g_key_file_set_string(keyfile, "gt", "abc", "hi");

    /*keyfile写入配置文件*/
    if ((conf = g_key_file_to_data(keyfile, NULL, &error)) == NULL ||
        !g_file_set_contents(conf_file, conf, -1, &error)) {
        g_error_free(error);
        error = NULL;
    }

    /*销毁*/
    g_free(conf);
    g_free(conf_file);
    g_key_file_free(keyfile);

    return 0;
}

执行前配置文件:

编译以及执行结果:

执行后配置文件:

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
使用GLib可以方便地进行文件的读写操作。下面是一个简单的示例代码,演示了如何使用GLib读取文件内容并将其输出到控制台上: ```c #include <stdio.h> #include <glib.h> int main(void) { gchar *file_name = "test.txt"; gchar *file_contents = NULL; gsize file_size = 0; if (g_file_get_contents(file_name, &file_contents, &file_size, NULL)) { printf("File contents:\n%s\n", file_contents); g_free(file_contents); } else { printf("Failed to read file %s\n", file_name); } return 0; } ``` 上面的代码首先定义了一个文件名和一个用于存储文件内容的变量。然后,使用`g_file_get_contents()`函数读取文件内容,并将其存储在`file_contents`变量中。如果成功读取文件,则将文件内容输出到控制台,并释放`file_contents`变量。如果读取文件失败,则输出错误消息。 类似地,使用`g_file_set_contents()`函数可以将数据写入文件中。下面是一个简单的示例代码,演示了如何使用GLib将字符串写入文件中: ```c #include <stdio.h> #include <glib.h> int main(void) { gchar *file_name = "test.txt"; gchar *file_contents = "Hello, world!\n"; gsize file_size = strlen(file_contents); if (g_file_set_contents(file_name, file_contents, file_size, NULL)) { printf("File written successfully.\n"); } else { printf("Failed to write file %s\n", file_name); } return 0; } ``` 上面的代码首先定义了一个文件名和一个要写入文件中的字符串。然后,使用`g_file_set_contents()`函数将字符串写入文件中。如果成功写入文件,则输出成功消息。否则,输出错误消息。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值