19.6. String Handling

GLib defines a new type called a GString, which is similar to a standard C string but one that grows automatically. Its string data is null-terminated. What this gives you is protection from buffer overflow programming errors within your program. This is a very important feature, and hence I recommend that you make use of GStrings. GString itself has a simple public definition:

struct GString 
{
  gchar *str; /* Points to the string's current \0-terminated value. */
  gint len; /* Current length */
};

As you might expect, there are a number of operations you can do with a GString.

GString *g_string_new( gchar *init );

This constructs a GString, copying the string value of init into the GString and returning a pointer to it. NULL may be given as the argument for an initially empty GString.

void g_string_free( GString *string,
                    gint     free_segment );

This frees the memory for the given GString. If free_segment is TRUE, then this also frees its character data.

	     
GString *g_string_assign( GString     *lval,
                          const gchar *rval );

This copies the characters from rval into lval, destroying the previous contents of lval. Note that lval will be lengthened as necessary to hold the string's contents, unlike the standard strcpy() function.

The rest of these functions should be relatively obvious (the _c versions accept a character instead of a string):

	     
GString *g_string_truncate( GString *string,
                            gint     len );
			     
GString *g_string_append( GString *string,
                          gchar   *val );
			    
GString *g_string_append_c( GString *string,
                            gchar    c );
	
GString *g_string_prepend( GString *string,
                           gchar   *val );
			     
GString *g_string_prepend_c( GString *string,
                             gchar    c );
	
void g_string_sprintf( GString *string,
                       gchar   *fmt,
                       ...);
	
void g_string_sprintfa ( GString *string,
                         gchar   *fmt,
                         ... );