前言

关于GLib的介绍这里就不赘述了,具体API介绍可以去GLib API Reference查阅,这里只是记录一下使用相关API所遇到的一些坑。

相关API

字符串相关API

    GString *g_string_new(const gchar *init);
    GString *g_string_append(GString *string, const gchar *val);
    GString *g_string_prepend(GString *string, const gchar *val);
    gchar *g_string_free(GString *string, gboolean free_segment);

如果需要对字符串进行拼接操作,使用GString相关API是非常方便的。注意 g_string_new跟g_string_free一定要配套使用,否则会内存泄漏。
g_string_appendg_string_prepend都是直接在原字符串上操作,这点要切记。

字符转换相关API

    gchar *g_filename_display_basename(const gchar *filename);
    gchar *g_locale_from_utf8(const gchar *utf8string, gssize len, gsize *bytes_read, gsize *bytes_written, GError **error);
    gchar *g_locale_to_utf8(const gchar *opsysstring, gssize len, gsize *bytes_read, gsize *bytes_written, GError **error);

g_filename_display_basename 此函数的参数字符编码必须是UTF-8,否则返回的字符串为乱码
g_locale_from_utf8 此函数将参数字符串从UTF-8编码转换为程序当前的编码,一般是GB2312,一般用于读取UTF-8编码的文件
g_locale_to_utf8 此函数将参数字符串从程序当前编码转换为UTF-8
下面看个例子, 比如我们有个含中文的文件名 /data/test/哈哈.txt如果想获得 哈哈.txt,则必须首先使用 g_locale_to_utf8函数转换一次, 然后再去获取basename

    GString *string = g_string_new("/data/test/哈哈.txt");
    gchar *str = g_locale_to_utf8(string->str, string->len, NULL, NULL, NULL);
    gchar *basename = g_filename_display_basename(str);

如果想使用GString *类型保存basename,则必须重新申请内存块

    GString *basename_string = g_string_new(basename); 

千万别像下面这样做

    GString *string = g_string_new("/data/test/哈哈.txt");
    string->str = g_locale_to_utf8(string->str, string->len, NULL, NULL, NULL); 

如果像上面那样做,因为转换后的字符串长度跟转换前不一样,后续使用会出问题,g_locale_from_utf8 同理
注意 g_locale_to_utf8返回的char *需要手动释放内存

解析key-value文件API

    GKeyFile *g_key_file_new(void);
    gboolean g_key_file_load_from_file(GKeyFile *key_file, const gchar *file, GKeyFileFlags flags, GError **error);
    gint g_key_file_get_integer(GKeyFile *key_file, const gchar *group_name,  const gchar *key, GError **error);
    gchar *g_key_file_get_string(GKeyFile *key_file, const gchar *group_name, const gchar *key, GError **error);
    void g_key_file_free(GKeyFile *key_file);

这几个API很好理解,用来解析具有键值对特征的文件,g_key_file_newg_key_file_free配套使用;
g_key_file_load_from_file的第二个参数的字符编码格式为UTF-8,在使用时一定要先转换一次;

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐