glib,如何处理GError的东西

glib, how to handle GError stuffs?

本文关键字:GError 处理 何处理 glib      更新时间:2023-10-16

我有这个功能:

static
void ReadFilesInDirectory(const std::string &target)
{
    GDir *dir;
    GError *error;
    const gchar *filename;
    gchar* pathPlusFilename;
    dir = g_dir_open(target.c_str(), 0, &error);
    while ((filename = g_dir_read_name(dir)))
    {
        pathPlusFilename = g_build_filename(target.c_str(),filename,(gchar*)NULL);
        if( g_file_test(pathPlusFilename ,G_FILE_TEST_IS_REGULAR) )
        {
            std::cout << "(file)      " << pathPlusFilename << std::endl;
        }
        else
        {
            if( g_file_test(pathPlusFilename ,G_FILE_TEST_IS_DIR) )
            {
                std::cout << "(directory) " << pathPlusFilename << std::endl;
                chdir(filename);
                ReadFilesInDirectory(pathPlusFilename);
            }
        }
    }
    if(error) g_error_free(error); // gives an error at running time
    g_free(pathPlusFilename);
    g_dir_close(dir);
}

有一个 GError 变量,但我不知道如何从 GError 打印一些东西,http://sourcecodebrowser.com/glib2.0/2.25.8/gerror_8h.html.仅通过来自 main 的简单调用运行该代码,

 ReadFilesInDirectory("/home/user/pictures")

导致运行时出错。

GLib参考手册中的错误报告部分对此进行了解释。 基本上:

GError *error = nullptr; //!\
dir = g_dir_open(target.c_str(), 0, &error);
if( error != NULL )
{
    std::cout << error->message << std::endl;
    g_clear_error (&error);
}