Search code examples
cstringerror-handlingglib

Creating a new String in C for use in a large library (GLib) without using fprintf


(While this question may seem specific to GLib or error handling at first, you don't really need to know anything about those to answer my question.)

I'm attempting to use g_set_error from GLib to handle my deleting file error correctly. I'm not super great with C, but my gut told me doing something like the following might be okay (3rd line):

void file_delete(const gchar *name) {
    if (remove(name) != 0) {
        gchar *errmsg = ("Error deleting file %s: %s.", name, strerror(errno));
        g_set_error(NULL, SDS_ERROR, 0, errmsg);
    }
    else {
        //log file <name> deleted
    }
}

Is it okay to create a new String this way? Or should I split errmsg into 3 separate Strings and concatenate them? Or some other method?


Solution

  • No, you can't create a string like that, that would return the result of strerror(errno).

    In my opinion, it would be best to concatenate multiple strings together.

    However, you could instead do this:

    gchar *errmsg = malloc(256); // change this size as needed
    snprintf(255, errmsg, "Error deleting file %s: %s.", name, strerror(errno));
    

    If you would prefer format strings, but don't forget to free(errmsg).

    UPDATE

    Also, as @Kninnug said in the comments of the question:

    Since you're using GLib already, might as well use their string utility methods, such as g_strdup_printf