pub struct KeyFile { /* private fields */ }
Expand description
GKeyFile
parses .ini-like config files.
GKeyFile
lets you parse, edit or create files containing groups of
key-value pairs, which we call “key files” for lack of a better name.
Several freedesktop.org specifications use key files now, e.g the
Desktop Entry Specification
and the Icon Theme Specification.
The syntax of key files is described in detail in the Desktop Entry Specification, here is a quick summary: Key files consists of groups of key-value pairs, interspersed with comments.
⚠️ The following code is in txt ⚠️
# this is just an example
# there can be comments before the first group
[First Group]
Name=Key File Example\tthis value shows\nescaping
# localized strings are stored in multiple key-value pairs
Welcome=Hello
Welcome[de]=Hallo
Welcome[fr_FR]=Bonjour
Welcome[it]=Ciao
[Another Group]
Numbers=2;20;-200;0
Booleans=true;false;true;true
Lines beginning with a ‘#’ and blank lines are considered comments.
Groups are started by a header line containing the group name enclosed in ‘[’ and ‘]’, and ended implicitly by the start of the next group or the end of the file. Each key-value pair must be contained in a group.
Key-value pairs generally have the form key=value
, with the exception
of localized strings, which have the form key[locale]=value
, with a
locale identifier of the form lang_COUNTRY@MODIFIER
where COUNTRY
and MODIFIER
are optional. Space before and after the ‘=’ character
are ignored. Newline, tab, carriage return and backslash characters in
value are escaped as \n
, \t
, \r
, and \\\\
, respectively. To preserve
leading spaces in values, these can also be escaped as \s
.
Key files can store strings (possibly with localized variants), integers, booleans and lists of these. Lists are separated by a separator character, typically ‘;’ or ‘,’. To use the list separator character in a value in a list, it has to be escaped by prefixing it with a backslash.
This syntax is obviously inspired by the .ini files commonly met on Windows, but there are some important differences:
-
.ini files use the ‘;’ character to begin comments, key files use the ‘#’ character.
-
Key files do not allow for ungrouped keys meaning only comments can precede the first group.
-
Key files are always encoded in UTF-8.
-
Key and Group names are case-sensitive. For example, a group called [GROUP] is a different from [group].
-
.ini files don’t have a strongly typed boolean entry type, they only have GetProfileInt(). In key files, only true and false (in lower case) are allowed.
Note that in contrast to the Desktop Entry Specification, groups in key files may contain the same key multiple times; the last entry wins. Key files may also contain multiple groups with the same name; they are merged together. Another difference is that keys and group names in key files are not restricted to ASCII characters.
Here is an example of loading a key file and reading a value:
⚠️ The following code is in c ⚠️
g_autoptr(GError) error = NULL;
g_autoptr(GKeyFile) key_file = g_key_file_new ();
if (!g_key_file_load_from_file (key_file, "key-file.ini", flags, &error))
{
if (!g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_NOENT))
g_warning ("Error loading key file: %s", error->message);
return;
}
g_autofree gchar *val = g_key_file_get_string (key_file, "Group Name", "SomeKey", &error);
if (val == NULL &&
!g_error_matches (error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_KEY_NOT_FOUND))
{
g_warning ("Error finding key in key file: %s", error->message);
return;
}
else if (val == NULL)
{
// Fall back to a default value.
val = g_strdup ("default-value");
}
Here is an example of creating and saving a key file:
⚠️ The following code is in c ⚠️
g_autoptr(GKeyFile) key_file = g_key_file_new ();
const gchar *val = …;
g_autoptr(GError) error = NULL;
g_key_file_set_string (key_file, "Group Name", "SomeKey", val);
// Save as a file.
if (!g_key_file_save_to_file (key_file, "key-file.ini", &error))
{
g_warning ("Error saving key file: %s", error->message);
return;
}
// Or store to a GBytes for use elsewhere.
gsize data_len;
g_autofree guint8 *data = (guint8 *) g_key_file_to_data (key_file, &data_len, &error);
if (data == NULL)
{
g_warning ("Error saving key file: %s", error->message);
return;
}
g_autoptr(GBytes) bytes = g_bytes_new_take (g_steal_pointer (&data), data_len);
GLib type: Shared boxed type with reference counted clone semantics.
Implementations§
Source§impl KeyFile
impl KeyFile
Sourcepub fn new() -> KeyFile
pub fn new() -> KeyFile
Creates a new empty #GKeyFile object. Use g_key_file_load_from_file(), g_key_file_load_from_data(), g_key_file_load_from_dirs() or g_key_file_load_from_data_dirs() to read an existing key file.
§Returns
an empty #GKeyFile.
Sourcepub fn comment(
&self,
group_name: Option<&str>,
key: Option<&str>,
) -> Result<GString, Error>
pub fn comment( &self, group_name: Option<&str>, key: Option<&str>, ) -> Result<GString, Error>
Retrieves a comment above @key from @group_name.
If @key is None
then @comment will be read from above
@group_name. If both @key and @group_name are None
, then
@comment will be read from above the first group in the file.
Note that the returned string does not include the ‘#’ comment markers, but does include any whitespace after them (on each line). It includes the line breaks between lines, but does not include the final line break.
§group_name
a group name, or None
§key
a key
§Returns
a comment that should be freed with g_free()
Sourcepub fn double(&self, group_name: &str, key: &str) -> Result<f64, Error>
pub fn double(&self, group_name: &str, key: &str) -> Result<f64, Error>
Returns the value associated with @key under @group_name as a
double. If @group_name is None
, the start_group is used.
If @key cannot be found then 0.0 is returned and @error is set to
KeyFileError::KeyNotFound
. Likewise, if the value associated
with @key cannot be interpreted as a double then 0.0 is returned
and @error is set to KeyFileError::InvalidValue
.
§group_name
a group name
§key
a key
§Returns
the value associated with the key as a double, or 0.0 if the key was not found or could not be parsed.
Sourcepub fn double_list(
&self,
group_name: &str,
key: &str,
) -> Result<Vec<f64>, Error>
pub fn double_list( &self, group_name: &str, key: &str, ) -> Result<Vec<f64>, Error>
Returns the values associated with @key under @group_name as doubles.
If @key cannot be found then None
is returned and @error is set to
KeyFileError::KeyNotFound
. Likewise, if the values associated
with @key cannot be interpreted as doubles then None
is returned
and @error is set to KeyFileError::InvalidValue
.
§group_name
a group name
§key
a key
§Returns
the values associated with the key as a list of doubles, or [`None`] if the
key was not found or could not be parsed. The returned list of doubles
should be freed with g_free() when no longer needed.
Sourcepub fn int64(&self, group_name: &str, key: &str) -> Result<i64, Error>
pub fn int64(&self, group_name: &str, key: &str) -> Result<i64, Error>
Returns the value associated with @key under @group_name as a signed 64-bit integer. This is similar to g_key_file_get_integer() but can return 64-bit results without truncation.
§group_name
a non-None
group name
§key
a non-None
key
§Returns
the value associated with the key as a signed 64-bit integer, or 0 if the key was not found or could not be parsed.
Sourcepub fn integer(&self, group_name: &str, key: &str) -> Result<i32, Error>
pub fn integer(&self, group_name: &str, key: &str) -> Result<i32, Error>
Returns the value associated with @key under @group_name as an integer.
If @key cannot be found then 0 is returned and @error is set to
KeyFileError::KeyNotFound
. Likewise, if the value associated
with @key cannot be interpreted as an integer, or is out of range
for a #gint, then 0 is returned
and @error is set to KeyFileError::InvalidValue
.
§group_name
a group name
§key
a key
§Returns
the value associated with the key as an integer, or 0 if the key was not found or could not be parsed.
Sourcepub fn integer_list(
&self,
group_name: &str,
key: &str,
) -> Result<Vec<i32>, Error>
pub fn integer_list( &self, group_name: &str, key: &str, ) -> Result<Vec<i32>, Error>
Returns the values associated with @key under @group_name as integers.
If @key cannot be found then None
is returned and @error is set to
KeyFileError::KeyNotFound
. Likewise, if the values associated
with @key cannot be interpreted as integers, or are out of range for
#gint, then None
is returned
and @error is set to KeyFileError::InvalidValue
.
§group_name
a group name
§key
a key
§Returns
the values associated with the key as a list of integers, or [`None`] if
the key was not found or could not be parsed. The returned list of
integers should be freed with g_free() when no longer needed.
Sourcepub fn locale_for_key(
&self,
group_name: &str,
key: &str,
locale: Option<&str>,
) -> Option<GString>
pub fn locale_for_key( &self, group_name: &str, key: &str, locale: Option<&str>, ) -> Option<GString>
Returns the actual locale which the result of g_key_file_get_locale_string() or g_key_file_get_locale_string_list() came from.
If calling g_key_file_get_locale_string() or g_key_file_get_locale_string_list() with exactly the same @self, @group_name, @key and @locale, the result of those functions will have originally been tagged with the locale that is the result of this function.
§group_name
a group name
§key
a key
§locale
a locale identifier or None
§Returns
the locale from the file, or None
if the key was not
found or the entry in the file was was untranslated
Sourcepub fn start_group(&self) -> Option<GString>
pub fn start_group(&self) -> Option<GString>
Sourcepub fn uint64(&self, group_name: &str, key: &str) -> Result<u64, Error>
pub fn uint64(&self, group_name: &str, key: &str) -> Result<u64, Error>
Returns the value associated with @key under @group_name as an unsigned 64-bit integer. This is similar to g_key_file_get_integer() but can return large positive results without truncation.
§group_name
a non-None
group name
§key
a non-None
key
§Returns
the value associated with the key as an unsigned 64-bit integer, or 0 if the key was not found or could not be parsed.
Sourcepub fn value(&self, group_name: &str, key: &str) -> Result<GString, Error>
pub fn value(&self, group_name: &str, key: &str) -> Result<GString, Error>
Returns the raw value associated with @key under @group_name. Use g_key_file_get_string() to retrieve an unescaped UTF-8 string.
In the event the key cannot be found, None
is returned and
@error is set to KeyFileError::KeyNotFound
. In the
event that the @group_name cannot be found, None
is returned
and @error is set to KeyFileError::GroupNotFound
.
§group_name
a group name
§key
a key
§Returns
a newly allocated string or None
if the specified
key cannot be found.
Sourcepub fn load_from_bytes(
&self,
bytes: &Bytes,
flags: KeyFileFlags,
) -> Result<(), Error>
pub fn load_from_bytes( &self, bytes: &Bytes, flags: KeyFileFlags, ) -> Result<(), Error>
Sourcepub fn load_from_data(
&self,
data: &str,
flags: KeyFileFlags,
) -> Result<(), Error>
pub fn load_from_data( &self, data: &str, flags: KeyFileFlags, ) -> Result<(), Error>
Sourcepub fn load_from_file(
&self,
file: impl AsRef<Path>,
flags: KeyFileFlags,
) -> Result<(), Error>
pub fn load_from_file( &self, file: impl AsRef<Path>, flags: KeyFileFlags, ) -> Result<(), Error>
Loads a key file into an empty #GKeyFile structure.
If the OS returns an error when opening or reading the file, a
G_FILE_ERROR
is returned. If there is a problem parsing the file, a
G_KEY_FILE_ERROR
is returned.
This function will never return a KeyFileError::NotFound
error. If the
@file is not found, FileError::Noent
is returned.
§file
the path of a filename to load, in the GLib filename encoding
§flags
flags from #GKeyFileFlags
§Returns
Sourcepub fn remove_comment(
&self,
group_name: Option<&str>,
key: Option<&str>,
) -> Result<(), Error>
pub fn remove_comment( &self, group_name: Option<&str>, key: Option<&str>, ) -> Result<(), Error>
Sourcepub fn set_boolean(&self, group_name: &str, key: &str, value: bool)
pub fn set_boolean(&self, group_name: &str, key: &str, value: bool)
Sourcepub fn set_comment(
&self,
group_name: Option<&str>,
key: Option<&str>,
comment: &str,
) -> Result<(), Error>
pub fn set_comment( &self, group_name: Option<&str>, key: Option<&str>, comment: &str, ) -> Result<(), Error>
Places a comment above @key from @group_name.
If @key is None
then @comment will be written above @group_name.
If both @key and @group_name are None
, then @comment will be
written above the first group in the file.
Note that this function prepends a ‘#’ comment marker to each line of @comment.
§group_name
a group name, or None
§key
a key
§comment
a comment
§Returns
Sourcepub fn set_double(&self, group_name: &str, key: &str, value: f64)
pub fn set_double(&self, group_name: &str, key: &str, value: f64)
Sourcepub fn set_integer(&self, group_name: &str, key: &str, value: i32)
pub fn set_integer(&self, group_name: &str, key: &str, value: i32)
Sourcepub fn set_list_separator(&self, separator: Char)
pub fn set_list_separator(&self, separator: Char)
Sets the character which is used to separate values in lists. Typically ‘;’ or ‘,’ are used as separators. The default list separator is ‘;’.
§separator
the separator
Sourcepub fn set_string(&self, group_name: &str, key: &str, string: &str)
pub fn set_string(&self, group_name: &str, key: &str, string: &str)
Associates a new string value with @key under @group_name. If @key cannot be found then it is created. If @group_name cannot be found then it is created. Unlike g_key_file_set_value(), this function handles characters that need escaping, such as newlines.
§group_name
a group name
§key
a key
§string
a string
Sourcepub fn set_uint64(&self, group_name: &str, key: &str, value: u64)
pub fn set_uint64(&self, group_name: &str, key: &str, value: u64)
Sourcepub fn set_value(&self, group_name: &str, key: &str, value: &str)
pub fn set_value(&self, group_name: &str, key: &str, value: &str)
Associates a new value with @key under @group_name.
If @key cannot be found then it is created. If @group_name cannot be found then it is created. To set an UTF-8 string which may contain characters that need escaping (such as newlines or spaces), use g_key_file_set_string().
§group_name
a group name
§key
a key
§value
a string
Source§impl KeyFile
impl KeyFile
Sourcepub fn save_to_file<T: AsRef<Path>>(&self, filename: T) -> Result<(), Error>
pub fn save_to_file<T: AsRef<Path>>(&self, filename: T) -> Result<(), Error>
Writes the contents of @self to @filename using g_file_set_contents(). If you need stricter guarantees about durability of the written file than are provided by g_file_set_contents(), use g_file_set_contents_full() with the return value of g_key_file_to_data().
This function can fail for any of the reasons that g_file_set_contents() may fail.
§filename
the name of the file to write to
§Returns
Sourcepub fn load_from_data_dirs<T: AsRef<Path>>(
&self,
file: T,
flags: KeyFileFlags,
) -> Result<PathBuf, Error>
pub fn load_from_data_dirs<T: AsRef<Path>>( &self, file: T, flags: KeyFileFlags, ) -> Result<PathBuf, Error>
This function looks for a key file named @file in the paths
returned from g_get_user_data_dir() and g_get_system_data_dirs(),
loads the file into @self and returns the file’s full path in
@full_path. If the file could not be loaded then an error
is
set to either a #GFileError or #GKeyFileError.
§file
a relative path to a filename to open and parse
§flags
flags from #GKeyFileFlags
§Returns
true
if a key file could be loaded, false
otherwise
§full_path
return location for a string containing the full path
of the file, or None
Sourcepub fn load_from_dirs<T: AsRef<Path>, U: AsRef<Path>>(
&self,
file: T,
search_dirs: &[U],
flags: KeyFileFlags,
) -> Result<PathBuf, Error>
pub fn load_from_dirs<T: AsRef<Path>, U: AsRef<Path>>( &self, file: T, search_dirs: &[U], flags: KeyFileFlags, ) -> Result<PathBuf, Error>
This function looks for a key file named @file in the paths specified in @search_dirs, loads the file into @self and returns the file’s full path in @full_path.
If the file could not be found in any of the @search_dirs,
KeyFileError::NotFound
is returned. If
the file is found but the OS returns an error when opening or reading the
file, a G_FILE_ERROR
is returned. If there is a problem parsing the file, a
G_KEY_FILE_ERROR
is returned.
§file
a relative path to a filename to open and parse
§search_dirs
None
-terminated array of directories to search
§flags
flags from #GKeyFileFlags
§Returns
true
if a key file could be loaded, false
otherwise
§full_path
return location for a string containing the full path
of the file, or None
Sourcepub fn groups(&self) -> PtrSlice<GStringPtr>
pub fn groups(&self) -> PtrSlice<GStringPtr>
Sourcepub fn keys(&self, group_name: &str) -> Result<PtrSlice<GStringPtr>, Error>
pub fn keys(&self, group_name: &str) -> Result<PtrSlice<GStringPtr>, Error>
Returns all keys for the group name @group_name. The array of
returned keys will be None
-terminated, so @length may
optionally be None
. In the event that the @group_name cannot
be found, None
is returned and @error is set to
KeyFileError::GroupNotFound
.
§group_name
a group name
§Returns
a newly-allocated None
-terminated array of strings.
Use g_strfreev() to free it.
§length
return location for the number of keys returned, or None
Sourcepub fn boolean(&self, group_name: &str, key: &str) -> Result<bool, Error>
pub fn boolean(&self, group_name: &str, key: &str) -> Result<bool, Error>
Returns the value associated with @key under @group_name as a boolean.
If @key cannot be found then false
is returned and @error is set
to KeyFileError::KeyNotFound
. Likewise, if the value
associated with @key cannot be interpreted as a boolean then false
is returned and @error is set to KeyFileError::InvalidValue
.
§group_name
a group name
§key
a key
§Returns
the value associated with the key as a boolean,
or false
if the key was not found or could not be parsed.
Sourcepub fn has_key(&self, group_name: &str, key: &str) -> Result<bool, Error>
pub fn has_key(&self, group_name: &str, key: &str) -> Result<bool, Error>
Looks whether the key file has the key @key in the group @group_name.
Note that this function does not follow the rules for #GError strictly;
the return value both carries meaning and signals an error. To use
this function, you must pass a #GError pointer in @error, and check
whether it is not None
to see if an error occurred.
Language bindings should use g_key_file_get_value() to test whether or not a key exists.
§group_name
a group name
§key
a key name
§Returns
Sourcepub fn boolean_list(
&self,
group_name: &str,
key: &str,
) -> Result<Vec<bool>, Error>
pub fn boolean_list( &self, group_name: &str, key: &str, ) -> Result<Vec<bool>, Error>
Returns the values associated with @key under @group_name as booleans.
If @key cannot be found then None
is returned and @error is set to
KeyFileError::KeyNotFound
. Likewise, if the values associated
with @key cannot be interpreted as booleans then None
is returned
and @error is set to KeyFileError::InvalidValue
.
§group_name
a group name
§key
a key
§Returns
the values associated with the key as a list of booleans, or None
if the
key was not found or could not be parsed. The returned list of booleans
should be freed with g_free() when no longer needed.
Sourcepub fn string(&self, group_name: &str, key: &str) -> Result<GString, Error>
pub fn string(&self, group_name: &str, key: &str) -> Result<GString, Error>
Returns the string value associated with @key under @group_name. Unlike g_key_file_get_value(), this function handles escape sequences like \s.
In the event the key cannot be found, None
is returned and
@error is set to KeyFileError::KeyNotFound
. In the
event that the @group_name cannot be found, None
is returned
and @error is set to KeyFileError::GroupNotFound
.
§group_name
a group name
§key
a key
§Returns
a newly allocated string or None
if the specified
key cannot be found.
Sourcepub fn string_list(
&self,
group_name: &str,
key: &str,
) -> Result<PtrSlice<GStringPtr>, Error>
pub fn string_list( &self, group_name: &str, key: &str, ) -> Result<PtrSlice<GStringPtr>, Error>
Returns the values associated with @key under @group_name.
In the event the key cannot be found, None
is returned and
@error is set to KeyFileError::KeyNotFound
. In the
event that the @group_name cannot be found, None
is returned
and @error is set to KeyFileError::GroupNotFound
.
§group_name
a group name
§key
a key
§Returns
a None
-terminated string array or None
if the specified
key cannot be found. The array should be freed with g_strfreev().
Sourcepub fn locale_string(
&self,
group_name: &str,
key: &str,
locale: Option<&str>,
) -> Result<GString, Error>
pub fn locale_string( &self, group_name: &str, key: &str, locale: Option<&str>, ) -> Result<GString, Error>
Returns the value associated with @key under @group_name
translated in the given @locale if available. If @locale is
None
then the current locale is assumed.
If @locale is to be non-None
, or if the current locale will change over
the lifetime of the #GKeyFile, it must be loaded with
KeyFileFlags::KEEP_TRANSLATIONS
in order to load strings for all locales.
If @key cannot be found then None
is returned and @error is set
to KeyFileError::KeyNotFound
. If the value associated
with @key cannot be interpreted or no suitable translation can
be found then the untranslated value is returned.
§group_name
a group name
§key
a key
§locale
a locale identifier or None
§Returns
a newly allocated string or None
if the specified
key cannot be found.
Sourcepub fn locale_string_list(
&self,
group_name: &str,
key: &str,
locale: Option<&str>,
) -> Result<PtrSlice<GStringPtr>, Error>
pub fn locale_string_list( &self, group_name: &str, key: &str, locale: Option<&str>, ) -> Result<PtrSlice<GStringPtr>, Error>
Returns the values associated with @key under @group_name
translated in the given @locale if available. If @locale is
None
then the current locale is assumed.
If @locale is to be non-None
, or if the current locale will change over
the lifetime of the #GKeyFile, it must be loaded with
KeyFileFlags::KEEP_TRANSLATIONS
in order to load strings for all locales.
If @key cannot be found then None
is returned and @error is set
to KeyFileError::KeyNotFound
. If the values associated
with @key cannot be interpreted or no suitable translations
can be found then the untranslated values are returned. The
returned array is None
-terminated, so @length may optionally
be None
.
§group_name
a group name
§key
a key
§locale
a locale identifier or None
§Returns
a newly allocated None
-terminated string array
or None
if the key isn’t found. The string array should be freed
with g_strfreev().
Trait Implementations§
Source§impl HasParamSpec for KeyFile
impl HasParamSpec for KeyFile
Source§impl Ord for KeyFile
impl Ord for KeyFile
Source§impl PartialOrd for KeyFile
impl PartialOrd for KeyFile
Source§impl StaticType for KeyFile
impl StaticType for KeyFile
Source§fn static_type() -> Type
fn static_type() -> Type
Self
.