Reputation: 3218
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.
Any string may be empty/NULL, as checked by every line before the printf.
Would be better if the complete print thing works as a function
Any better way of implementing this?
Upvotes: 0
Views: 512
Reputation: 121961
Eliminate the duplication that checks if the string is NULL
or empty by wrapping that in a function:
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);
Upvotes: 3