Utilities: Gwyddion Library Reference Manual

## Utilities Utilities — Miscellaneous utility functions |

## Functions

void | (*GwyNameFunc) ()
gboolean | (*GwySetFractionFunc) ()
gboolean | (*GwySetMessageFunc) ()
GQuark | gwy_parse_doubles_error_quark ()
gchar * | gwy_strkill ()
gchar * | gwy_strreplace ()
gint | gwy_strdiffpos ()
gboolean | gwy_ascii_strisident ()
gboolean | gwy_ascii_strcase_equal ()
guint | gwy_ascii_strcase_hash ()
guint | gwy_stramong ()
gpointer | gwy_memmem ()
gboolean | gwy_map_file_contents ()
void | gwy_unmap_file_contents ()
gchar * | gwy_find_self_path ()
const gchar * | gwy_get_user_dir ()
const gchar * | gwy_get_home_dir ()
gchar * | gwy_canonicalize_path ()
gboolean | gwy_filename_ignore ()
const gchar * | gwy_sgettext ()
gchar * | gwy_str_next_line ()
guint | gwy_str_fixed_font_width ()
guint | gwy_gstring_replace ()
void | gwy_gstring_to_native_eol ()
const gchar * | gwy_get_decimal_separator ()
void | gwy_append_doubles_to_gstring ()
gdouble * | gwy_parse_doubles ()
gchar * | gwy_convert_to_utf8 ()
gchar * | gwy_utf16_to_utf8 ()
gchar * | gwy_utf8_strescape ()
gboolean | gwy_assign_string ()
gboolean | gwy_assign_gstring ()
gboolean | gwy_assign_boxed ()
void | gwy_object_set_or_reset ()
gboolean | gwy_set_member_object ()
FILE * | gwy_fopen ()
int | gwy_fprintf ()

## Types and Values

enum | GwyParseDoublesFlags
enum | GwyParseDoublesError
#define | GWY_PARSE_DOUBLES_ERROR

## Includes

    #include <libgwyddion/gwyddion.h>

## Description

Various utility functions: creating GLib lists from hash tables `gwy_hash_table_to_list_cb()`), protably finding Gwyddion application directories (`gwy_find_self_dir()`), string functions (`gwy_strreplace()`), path manipulation (`gwy_canonicalize_path()`).

## Functions

### GwyNameFunc()

    void
    (*GwyNameFunc) (const gchar *name,
                    gpointer user_data);

Type of function passed to for-each functions enumerating items by name.

#### Parameters

name | Item name, owned by the caller. |
user_data | User data passed to the for-each function. |

### GwySetFractionFunc()

    gboolean
    (*GwySetFractionFunc) (gdouble fraction);

Type of function for reporting progress of a long computation.

Usually you want to use `gwy_app_wait_set_fraction()`.

#### Parameters

fraction | Progress estimate as a number from the interval [0,1]. |

#### Returns

`TRUE` if the computation should continue; `FALSE` if it should be cancelled.

### GwySetMessageFunc()

    gboolean
    (*GwySetMessageFunc) (const gchar *message);

Type of function for reporting what a long computation is doing now.

Usually you want to use `gwy_app_wait_set_message()`.

#### Parameters

message | Message to be shown together with the progress fraction. If the computation has stages the messages should reflect this. Otherwise at least some general message should be set. |

#### Returns

`TRUE` if the computation should continue; `FALSE` if it should be cancelled.

### gwy_parse_doubles_error_quark()

    GQuark
    gwy_parse_doubles_error_quark (void);

Returns error domain for floating point value parsing and evaluation.

See and use `GWY_PARSE_DOUBLES_ERROR`.

#### Returns

The error domain.

### gwy_strkill()

    gchar *
    gwy_strkill (gchar *s,
                 const gchar *killchars);

Removes characters in `killchars` from string `s` , modifying it in place.

Use gwy_strkill(g_strdup(`s` ), `killchars` ) to get a modified copy.

#### Parameters

s | A NUL-terminated string. |
killchars | A string containing characters to kill. |

#### Returns

`s` itself, the return value is to allow function call nesting.

### gwy_strreplace()

    gchar *
    gwy_strreplace (const gchar *haystack,
                    const gchar *needle,
                    const gchar *replacement,
                    gsize maxrepl);

Replaces occurences of string `needle` in `haystack` with `replacement` .

See `gwy_gstring_replace()` for a function which does in-place replacement on a GString.

#### Parameters

haystack | A NUL-terminated string to search in. |
needle | A NUL-terminated string to search for. |
replacement | A NUL-terminated string to replace `needle` with. |
maxrepl | Maximum number of occurences to replace (use (gsize)-1 to replace all occurences). |

#### Returns

A newly allocated string.

### gwy_strdiffpos()

    gint
    gwy_strdiffpos (const gchar *s1,
                    const gchar *s2);

Finds position where two strings differ.

#### Parameters

s1 | A string. | [nullable]
s2 | A string. | [nullable]

#### Returns

The last position where the strings do not differ yet. Possibly -1 can be returned if either string is `NULL`, zero-length, or they differ in the very first character.

### gwy_ascii_strisident()

    gboolean
    gwy_ascii_strisident (const gchar *s,
                          const gchar *more,
                          const gchar *startmore);

Checks whether a string is valid identifier.

Valid identifier must start with an alphabetic character or a character from `startmore` , and it must continue with alphanumeric characters or characters from `more` .

Note underscore is not allowed by default, you have to pass it in `more` and/or `startmore` .

#### Parameters

s | A NUL-terminated string. |
more | List of additional ASCII characters allowed inside identifier, empty list can be passed as `NULL`. | [nullable]
startmore | List of additional ASCII characters allowed as the first identifier characters, empty list can be passed as `NULL`. | [nullable]

#### Returns

`TRUE` if `s` is valid identifier, `FALSE` otherwise.

### gwy_ascii_strcase_equal()

    gboolean
    gwy_ascii_strcase_equal (gconstpointer v1,
                             gconstpointer v2);

Compares two strings for equality, ignoring case.

The case folding is performed only on ASCII characters.

This function is intended to be passed to `g_hash_table_new()` as `key_equal_func` , namely in conjuction with `gwy_ascii_strcase_hash()` hashing function.

#### Parameters

v1 | String key. |
v2 | String key to compare with `v1` . |

#### Returns

`TRUE` if the two string keys match, ignoring case.

### gwy_ascii_strcase_hash()

    guint
    gwy_ascii_strcase_hash (gconstpointer v);

Converts a string to a hash value, ignoring case.

The case folding is performed only on ASCII characters.

This function is intended to be passed to `g_hash_table_new()` as `hash_func` , namely in conjuction with `gwy_ascii_strcase_equal()` comparison function.

#### Parameters

v | String key. |

#### Returns

The hash value corresponding to the key `v` .

### gwy_stramong()

    guint
    gwy_stramong (const gchar *str,
                  ...);

Checks whether a string is equal to any from given list.

The return value is frequently treated as a boolean. Nevertheless, can be used to identify the matching string. On a match, the index of the first matching string is returned, plus one.

#### Parameters

str | A string to find. |
... | `NULL`-terminated list of string to compare `str` with. |

#### Returns

Zero if `str` does not equal to any string from the list, nozero othwerise.

### gwy_memmem()

    gpointer
    gwy_memmem (gconstpointer haystack,
                gsize haystack_len,
                gconstpointer needle,
                gsize needle_len);

Find a block of memory in another block of memory.

This function is very similar to `strstr()`, except that it works with arbitrary memory blocks instead of NUL-terminated strings.

If `needle_len` is zero, `haystack` is always returned.

On GNU systems with glibc at least 2.1 this is a just a trivial `memmem()` wrapper. On other systems it emulates `memmem()` behaviour but may be a bit slower.

#### Parameters

haystack | Memory block to search in. |
haystack_len | Size of `haystack` , in bytes. |
needle | Memory block to find. |
needle_len | Size of `needle` , in bytes. |

#### Returns

Pointer to the first byte of memory block in `haystack` that matches `needle` ; `NULL` if no such block exists.

### gwy_map_file_contents()

    gboolean
    gwy_map_file_contents (const gchar *filename,
                           const guchar **buffer,
                           gsize *size,
                           GError **error);

Maps file contents into memory for reading.

This is a convenience wrapper for GMappedFile which looks more like `g_file_get_contents()`. The mapping is read-only and must be later with `gwy_unmap_file_contents()`. Unlike `g_file_get_contents()`, the contents is NOT NUL-terminated. Use `size` to find its end.

Errors from the GFileError domain can occur.

#### Parameters

filename | A file to read contents of. |
buffer | Buffer to store the file contents. |
size | Location to store buffer (file) size. |
error | Return location for a GError. |

#### Returns

Whether it succeeded. In the case of failure `buffer` and `size` are reset too.

### gwy_unmap_file_contents()

    void
    gwy_unmap_file_contents (const guchar *buffer);

Ummaps a file mapped to memory for reading.

For convenience, it is possible to pass `NULL` `buffer` . The function is no-op then.

#### Parameters

buffer | Buffer with file contents as created by `gwy_map_file_contents()`. |

### gwy_find_self_path()

    gchar *
    gwy_find_self_path (const gchar *dirname,
                        ...);

Finds a system Gwyddion directory.

On all operating system, the directories can be overriden with environment variables which have the highest priority (see gwyddion manual page). Otherwise…

In an OS X bundle, a location in the bundle is returned.

On Unix, a compiled-in path is returned.

On Win32, the directory where the libgwyddion DLL from which this function was called resides is taken as the base and the location of other Gwyddion directories is calculated from it.

The returned value is not actually tested for existence. It is up to the caller.

Icons, modules and system resources like gradients reside in subdirectories. Use the additional path components to construct their path directly. If you are looking for a single file you can use them to construct path to this specific file, although usually one looks for directories.

To obtain the Gwyddion user directory see `gwy_get_user_dir()`.

#### Parameters

dirname | A gwyddion base directory name: `"lib"`, `"locale"`, or `"data"`. |
... | Additional path components, `NULL`-terminated. |

#### Returns

The path as a newly allocated string.

### gwy_get_user_dir()

    const gchar *
    gwy_get_user_dir (void);

Returns the directory where Gwyddion user settings and data should be stored.

On Unix this is usually a dot-directory in user's home directory. On modern Win32 the returned directory resides in user's Documents and Settings. On silly platforms or silly occasions, silly locations (namely a temporary directory) can be returned as fallback.

To obtain a Gwyddion system directory see `gwy_find_self_dir()`.

#### Returns

The directory as a constant string that should not be freed.

### gwy_get_home_dir()

    const gchar *
    gwy_get_home_dir (void);

Returns home directory, or temporary directory as a fallback.

Under normal circumstances the same string as `g_get_home_dir()` would return is returned. But on MS Windows, something like "C:\Windows\Temp" can be returned too, as it is as good as anything else (we can write there).

#### Returns

Something usable as user home directory. It may be silly, but never `NULL` or empty.

### gwy_canonicalize_path()

    gchar *
    gwy_canonicalize_path (const gchar *path);

Canonicalizes a filesystem path.

Particularly it makes the path absolute, resolves `..' and` .', and fixes slash sequences to single slashes. On Win32 it also converts all backslashes to slashes along the way.

Note this function does NOT resolve symlinks, use `g_file_read_link()` for that.

#### Parameters

path | A filesystem path. |

#### Returns

The canonical path, as a newly created string.

### gwy_filename_ignore()

    gboolean
    gwy_filename_ignore (const gchar *filename_sys);

Checks whether file should be ignored.

This function checks for common file names indicating files that should be normally ignored. Currently it means backup files (ending with ~ or .bak) and Unix hidden files (starting with a dot).

#### Parameters

filename_sys | File name in GLib encoding. |

#### Returns

`TRUE` to ignore this file, `FALSE` otherwise.

### gwy_sgettext()

    const gchar *
    gwy_sgettext (const gchar *domain,
                  const gchar *msgid);

Translate a message id containing disambiguating prefix ending with ‘\004’.

The control ASCII character 0x04 is used to separate message context in gettext and is used by macros such as `C_()`. It is not allowed in translatable strings.

If the message is translated then the translation is returned. If it is not translated and it contains the character ‘\004’ a pointer into `msgid` is returned, to the byte after the separator character.

If you can pass both the context and message separately, use the standard macros. Whenever you would need to write ‘\004’ literally or pass a literal string at all, it is probably an incorrect usage. In particular, in direct calls do

    1
    foo(C_("context", "Message"));

instead of

    1
    foo(gwy_C("context\004Message"));

However, using `NC_()` and `C_()` requires duplicating the context and/or passing them around separately. It is sometimes awkward or even not possible to pass the context where it is finally needed.

If you need to pass the context and message already in a single string (separated with ‘\004’) you can use this function. It is a simpler alternative to `g_dpgettext()` which tries to use both ‘|’ and ‘\004’ in a complicated manner when the context is not passed separately. You can use macro `gwy_NC()` to form source code strings with context. See also macro `GWY_C()` which expands to `gwy_sgettext()` with the first argument set to GETTEXT_PACKAGE.

The function uses `g_dgettext()` internally to avoid mixing translated and untranslated messages.

This function description is about ten times longer than the implementation. So the entire situation is clearly a mess.

#### Parameters

domain | Translation domain to use, or `NULL` for the domain set with `textdomain()`. | [nullable]
msgid | Message id to translate, possibly with ‘\004’-separated context prefix. |

#### Returns

Translated or untranslated message, but in all cases without any context prefix.

### gwy_str_next_line()

    gchar *
    gwy_str_next_line (gchar **buffer);

Extracts a next line from a character buffer, modifying it in place.

`buffer` is updated to point after the end of the line and the "\n" (or "\r" or "\r\n") is replaced with "\0", if present.

The final line may or may not be terminated with an EOL marker, its contents is returned in either case. Note, however, that the empty string "" is not interpreted as an empty unterminated line. Instead, `NULL` is immediately returned.

The typical usage of `gwy_str_next_line()` is:

    1
    2
    3
    4
    5
    6
    7
    gchar *p = text;
    for (gchar *line = gwy_str_next_line(&p);
         line;
         line = gwy_str_next_line(&p)) {
        g_strstrip(line);
        // Do something more with line
    }

#### Parameters

buffer | Text buffer. | [nullable]

#### Returns

The start of the line. `NULL` if the buffer is empty or `NULL`. The return value is not a new string; the normal return value is the previous value of `buffer` .

### gwy_str_fixed_font_width()

    guint
    gwy_str_fixed_font_width (const gchar *str);

Measures the width of UTF-8 encoded string in fixed-width font.

This corresponds to width of the string displayed on a text terminal, for instance. Zero and double width characters are taken into account. It is not guaranteed all terminals display the string with the calculated width.

#### Parameters

str | UTF-8 encoded string. |

#### Returns

String width in fixed font, in character cells.

### gwy_gstring_replace()

    guint
    gwy_gstring_replace (GString *str,
                         const gchar *old,
                         const gchar *replacement,
                         gint count);

Replaces non-overlapping occurrences of one string with another in a GString.

Passing `NULL` or the empty string for `replacement` will cause the occurrences of `old` to be removed.

Passing `NULL` or the empty string for `old` means a match occurs at every position in the string, including after the last character. So `replacement` will be inserted at every position in this case.

See `gwy_strreplace()` for a function which creates a new plain C string with substring replacement.

#### Parameters

str | A GString string to modify in place. |
old | The character sequence to find and replace. Passing `NULL` is the same as passing the empty string. | [nullable]
replacement | The character sequence that should replace `old` . Passing `NULL` is the same as passing the empty string. | [nullable]
count | The maximum number of replacements to make. A negative number means replacing all occurrences of `old` . Note zero means just zero, i.e. no replacements are made. |

#### Returns

The number of replacements made. A non-zero value means the string has been modified, no-op replacements do not count.

### gwy_gstring_to_native_eol()

    void
    gwy_gstring_to_native_eol (GString *str);

Converts "\n" in a string to operating system native line terminators.

Text files are most easily written by opening them in the text mode. This function can be useful for writing text files using functions such as `g_file_set_contents()` that do not permit the conversion to happen automatically.

It is a no-op on all POSIX systems, including OS X. So at present, it actually performs any conversion at all only on MS Windows.

#### Parameters

str | A GString string to modify in place. |

### gwy_get_decimal_separator()

    const gchar *
    gwy_get_decimal_separator (void);

Find the decimal separator for the current locale.

This is a `localeconv()` wrapper.

#### Returns

The decimal separator for the current locale as a static string.

### gwy_append_doubles_to_gstring()

    void
    gwy_append_doubles_to_gstring (GString *str,
                                   const gdouble *values,
                                   guint n,
                                   gint precision,
                                   const gchar *field_separator,
                                   gboolean force_decimal_dot);

Formats a sequence of double values to a GString.

#### Parameters

str | String to append the formated numbers to. |
values | Array of double values to format. | [array length=n]
n | Number of values in `values` to format. |
precision | Format precision, within the standard precision of double. |
field_separator | String to put between each two formatted numbers, usually a space or tab character. |
force_decimal_dot | `TRUE` to ensure the numbers use a decimal dot, regardless of locale. `FALSE` to honour the current locale. |

### gwy_parse_doubles()

    gdouble *
    gwy_parse_doubles (const gchar *s,
                       gdouble *values,
                       GwyParseDoublesFlags flags,
                       gint *nlines,
                       gint *ncols,
                       gchar **endptr,
                       GError **error);

Parse a block of text floating point values.

Any combinations of a priori known and unknown dimensions is possible. For an unknown number of columns the number of columns must still be the same on each line, unless the flag `GWY_PARSE_DOUBLES_FREE_FORM` is passed. If any dimension is unknown, `values` cannot be preallocated as must be `NULL`.

Currently the values must be whitespace separated and in the POSIX format.

If the flag `GWY_PARSE_DOUBLES_EMPTY` is passed and the string contains not data, it is not considered an error and `error` is not set. However, the function returns `NULL` in such case. If you allow empty data you need to check the error to distinguish them from failure.

#### Parameters

s | String with floating point data to parse. |
values | Pre-allocated array where to store values (for a fixed number of values). |
flags | Parsing flags. |
nlines | Location where to store the number of lines. Initialise to the number of lines for a fixed number of lines or to -1 for unknown. The value is only changed if initially -1. |
ncols | Location where to store the number of columns. Initialise to the number of columns for a fixed number of columns or to -1 for unknown. The value is only changed if initially -1. |
endptr | Location where to store pointer after the last parsed character in `s` . Possibly `NULL`. | [nullable]
error | Return location for a GError. |

#### Returns

On success, either `values` (if non-`NULL` `values` was passed) or a newly allocated array with the data. On failure, `NULL` is returned.

### gwy_convert_to_utf8()

    gchar *
    gwy_convert_to_utf8 (const guchar *str,
                         glong len,
                         const gchar *codeset);

Converts a string to UTF-8.

This is a `g_convert()` wrapper for the typical SPM file reading use case. Conversion failure is indicated just by a `NULL` return value. Conversion is either completely successful or fails. Use `g_convert()` or `g_iconv()` if you need to handle partial conversions and failure details.

#### Parameters

str | A string to convert to UTF-8. |
len | Maximum string length. May be -1 if `str` is NUL-terminated. |
codeset | String code set, for instance "ISO-8859-1" or "CP1251". |

#### Returns

A newly allocated string on success; `NULL` on failure.

### gwy_utf16_to_utf8()

    gchar *
    gwy_utf16_to_utf8 (const gunichar2 *str,
                       glong len,
                       GwyByteOrder byteorder);

Convert a string from UTF-16 to UTF-8. The result will be terminated with a 0 byte.

This functions differs from `g_utf16_to_utf8()` mainly by the handling of byte order. In particular, the caller specifies the byte order explicitly and it can differ from the native byte order.

It is possible to pass `GWY_BYTE_ORDER_IMPLICIT` as `byteorder` . In such case `str` is checked for a byte-order mark. When one is present it is used for the byte order. Otherwise the behaviour is the same as for `GWY_BYTE_ORDER_NATIVE`. The output string never begins with a byte-order mark.

Conversion failure is indicated just by a `NULL` return value. Conversion is either completely successful or fails. Use `g_utf16_to_utf8()` if you need to handle partial conversions and failure details.

#### Parameters

str | A UTF-16 encoded string. |
len | Maximum string length (number of gunichar2 items in `str` , NOT the number of bytes). May be -1 if `str` is nul-terminated. |
byteorder | Byte order of `str` . |

#### Returns

A newly allocated string on success; `NULL` on failure.

### gwy_utf8_strescape()

    gchar *
    gwy_utf8_strescape (const gchar *source,
                        const gchar *exceptions);

Escapes special characters in a string.

Escapes the special characters '\b', '\f', '\n', '\r', '\t', '\v', '\' and '"' in the string source by writing them using the above-mentioned escape sequences or inserting a '\' before them. Additionally all characters in the range 0x01-0x1F (everything below SPACE), the character 0x7F, characters 0xC0 and 0xC1, and all characters in the range 0xF5-0xFF are replaced with a '\' followed by their octal representation. Characters supplied in exceptions are not escaped.

In essence, this functions differs from `g_strescape()` by preserving valid UTF-8 strings, unless they contain ‘odd’ characters. Passing strings which are not valid UTF-8 is possible, but generally not advised.

Function `g_strcompress()` does the reverse conversion.

#### Parameters

source | A string to escape. |
exceptions | A string containing characters to not escape, or `NULL`. | [nullable]

#### Returns

A newly allocated string with special characters escaped.

### gwy_assign_string()

    gboolean
    gwy_assign_string (gchar **target,
                       const gchar *newvalue);

Assigns a string, checking for equality and handling `NULL`s.

This function simplifies handling of string value setters.

The new value is duplicated and the old string is freed in a safe manner (it is possible to pass a pointer somewhere within the old value as the new value, for instance). Any of the old and new value can be `NULL`. If both values are equal (including both unset), the function returns `FALSE`.

#### Parameters

target | Pointer to target string, typically a struct field. |
newvalue | New value of the string, may be `NULL`. | [nullable]

#### Returns

`TRUE` if the target string has changed.

### gwy_assign_gstring()

    gboolean
    gwy_assign_gstring (GString *str,
                        const gchar *newvalue);

Assings a string to a GString.

This function is very similar to `g_string_assign()`, with two exceptions.

First, the new value can be `NULL`, with the same meaning as an empty string. It makes `gwy_assign_gstring()` simpler and less error prone to use if the string originates from some getter which may also return a `NULL`.

Second, the return value indicates whether the string has changed. It makes it less useful for chaining string operations but more useful for chaining logic and creating fast paths.

#### Parameters

str | A GString. |
newvalue | New value of the string, may be `NULL`. | [nullable]

#### Returns

`TRUE` if the contents of `str` has changed; `FALSE` if it has not.

### gwy_assign_boxed()

    gboolean
    gwy_assign_boxed (gpointer *target,
                      gconstpointer newvalue,
                      GType boxed_type);

Assigns a serialisable boxed value, checking for equality and handling `NULL`s.

This function simplifies handling of serialisable boxed value setters, using `gwy_serializable_boxed_equal()` and `gwy_serializable_boxed_assign()` for correct comparison and value assignment.

Any of the old and new value can be `NULL`. If both values are equal (including both unset), the function returns `FALSE`.

#### Parameters

target | Pointer to target boxed, typically a struct field. |
newvalue | New value of the boxed, may be `NULL`. | [nullable]
boxed_type | Type of the boxed value. It must be a registered serialisable type (see `gwy_serializable_boxed_register_static()`). |

#### Returns

`TRUE` if the target boxed has changed.

### gwy_object_set_or_reset()

    void
    gwy_object_set_or_reset (gpointer object,
                             GType type,
                             ...);

Sets object properties, resetting other properties to defaults.

All explicitly specified properties are set. In addition, all unspecified settable properties of type `type` (or all unspecified properties if `type` is 0) are reset to defaults. Settable means the property is writable and not construction-only.

The order in which properties are set is undefined beside keeping the relative order of explicitly specified properties, therefore this function is not generally usable for objects with interdependent properties.

Unlike `g_object_set()`, it does not set properties that already have the requested value, as a consequences notifications are emitted only for properties which actually change.

#### Parameters

object | A GObject. |
type | The type whose properties are to reset, may be zero for all types. The object must be of this type (more precisely `object` is-a `type` must hold). |
... | `NULL`-terminated list of name/value pairs of properties to set as in `g_object_set()`. It can be `NULL` alone to only reset properties to defaults. |

### gwy_set_member_object()

    gboolean
    gwy_set_member_object (gpointer instance,
                           gpointer member_object,
                           GType expected_type,
                           gpointer member_field,
                           ...);

Replaces a member object of another object, handling signal connection and disconnection.

If `member_object` is not `NULL` a reference is taken, sinking any floating objects (and conversely, the reference to the previous member object is released).

The purpose is to simplify bookkeeping in classes that have settable member objects and (usually but not necessarily) need to connect to some signals of these member objects. Since this function both connects and disconnects signals it must be always called with the same set of signals, including callbacks and flags, for a specific member object.

Example for a GwyFoo class owning a GwyGradient member object, assuming the usual conventions:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    typedef struct _GwyFooPrivate GwyFooPrivate;

    struct _GwyFooPrivate {
        GwyGradient *gradient;
        gulong gradient_data_changed_id;
    };

    static gboolean
    set_gradient(GwyFoo *foo)
    {
        GwyFooPrivate *priv = G_TYPE_INSTANCE_GET_PRIVATE(foo, GWY_TYPE_FOO,
                                                          GwyFooPrivate);
        if (!gwy_set_member_object(foo, gradient, GWY_TYPE_GRADIENT,
                                   &priv->gradient,
                                   "data-changed", &foo_gradient_data_changed,
                                   &priv->gradient_data_changed_id,
                                   G_CONNECT_SWAPPED,
                                   NULL))
            return FALSE;

        // Do whatever else needs to be done if the gradient changes.
        return TRUE;
    }

The gradient setter then usually only calls ``set_gradient()`` and disposing of the member object again only calls ``set_gradient()`` but with `NULL` gradient.

#### Parameters

instance | An object instance. |
member_object | Another object to be owned by `instanced` , or `NULL`. |
expected_type | The type of `member_object` . It is checked and a critical message is emitted if it does not conform. |
member_field | Pointer to location storing the current member object to be replaced by `member_object` . |
... | List of quadruplets of the form signal name, GCallback callback, gulong pointer to location to hold the signal handler id, and GConnectFlags connection flags. |

#### Returns

`TRUE` if `member_field` was changed. `FALSE` means the new member is identical to the current one and the function reduced to no-op (or that an assertion faled).

### gwy_fopen()

    FILE *
    gwy_fopen (const char *filename,
               const char *mode);

A wrapper for the stdio `fopen()` function. The `fopen()` function opens a file and associates a new stream with it.

Because file descriptors are specific to the C library on Windows, and a file descriptor is part of the FILE struct, the FILE* returned by this function makes sense only to functions in the same C library. Thus if the GLib-using code uses a different C library than GLib does, the FILE* returned by this function cannot be passed to C library functions like `fprintf()` or `fread()`.

See your C library manual for more details about `fopen()`.

#### Parameters

filename | a pathname in the GLib file name encoding (UTF-8 on Windows) |
mode | a string describing the mode in which the file should be opened |

#### Returns

A FILE* if the file was successfully opened, or `NULL` if an error occurred.

### gwy_fprintf()

    int
    gwy_fprintf (FILE *file,
                 char const *format,
                 ...);

An implementation of the standard `fprintf()` function which supports positional parameters, as specified in the Single Unix Specification.

#### Parameters

file | the stream to write to. |
format | a standard `printf()` format string, but notice string precision pitfalls |
... | the arguments to insert in the output. |

#### Returns

the number of bytes printed.

## Types and Values

### enum GwyParseDoublesFlags

Type of flags passed to `gwy_parse_doubles()`.

#### Members

GWY_PARSE_DOUBLES_EMPTY_OK | Do not set error (and return `NULL`) when there are no data. |
GWY_PARSE_DOUBLES_COMPLETELY | For unknown number of values, consider an error when they are followed by non-numerical garbage. This flag has no effect for a known number of values. |
GWY_PARSE_DOUBLES_FREE_FORM | Do not distinguish line breaks from other whitespace; just read the requested number of values. For an unknown number of values they will be reported as single-column. |

### enum GwyParseDoublesError

Type of error which can occur in `gwy_parse_doubles()`.

#### Members

GWY_PARSE_DOUBLES_EMPTY | There are no data at all. |
GWY_PARSE_DOUBLES_TRUNCATED | There are fewer values than expected. |
GWY_PARSE_DOUBLES_MALFORMED | Non-numerical garbage encounted before reading the expected number of values. |
GWY_PARSE_DOUBLES_NONUNIFORM | Lines do not have the expected constant number of columns. |

### GWY_PARSE_DOUBLES_ERROR

    #define GWY_PARSE_DOUBLES_ERROR gwy_parse_doubles_error_quark()

Error domain for parsing floating point data.

## See Also

gwymacros -- utility macros