0

I am writing some string to a gstring using printf as:

char *string<i> 
/*where string<i> stands for string1, string2
and so on*/
 g_string_append_printf (ustring, "@%s{%s,\n",string1, string0);
if( strlen(string2)!=0 ||string2!=NULL)
 g_string_append_printf (ustring,"\tAuthor=\"%s\",\n", string2);
if( strlen(string3)!=0 ||string3!=NULL)
 g_string_append_printf (ustring,"\tYear=\"%s\",\n", string3);
if( strlen(string4)!=0 ||string4!=NULL)
g_string_append_printf (ustring, "\tTitle=\"%s\",\n", string4);

GLib's are probably not exactly important here. Consider it as

printf ("\tAuthor=\"%s\",\n", string<i>)

When this works rather fine, it seems not the best way(i have strings string<1> to string<30>) and I am looking for some better way.

Points to consider

  1. Any string may be empty/NULL, as checked by every line before the printf.

  2. Would be better if the complete print thing works as a function

Any better way of implementing this?

4

1 回答 1

3

NULL通过将字符串包装在函数中来消除检查字符串是否为空的重复:

void conditionally_append_string(char* out, const char* fmt, const char* in)
{
    /* Check for NULL before dereferencing.
       Just check if first character is NOT null terminator
       instead of invoking strlen(). */
    if (in && *in)
    {
        g_string_append_printf (out, fmt, in);
    }
}

conditionally_append_string(ustring, "@%s{\n",             string0);
conditionally_append_string(ustring, "%s,\n",              string1);
conditionally_append_string(ustring, "\tAuthor=\"%s\",\n", string2);
于 2013-05-03T13:24:44.440 回答