Skip to Content

雜項實用函式

achi's 的頭像

雜項實用函式

雜項實用函式 — a selection of portable utility functions

 

一覽表

#include <glib.h>

const gchar* g_get_application_name (void);
void g_set_application_name (const gchar *application_name);
gchar* g_get_prgname (void);
void g_set_prgname (const gchar *prgname);
const gchar* g_getenv (const gchar *variable);
gboolean g_setenv (const gchar *variable,
const gchar *value,
gboolean overwrite);
void g_unsetenv (const gchar *variable);
gchar** g_listenv (void);
const gchar* g_get_user_name (void);
const gchar* g_get_real_name (void);
const gchar* g_get_user_cache_dir (void);
const gchar* g_get_user_data_dir (void);
const gchar* g_get_user_config_dir (void);
enum GUserDirectory;
const gchar* g_get_user_special_dir (GUserDirectory directory);
const gchar* const * g_get_system_data_dirs (void);
const gchar* const * g_get_system_config_dirs (void);
void g_reload_user_special_dirs_cache (void);

const gchar* g_get_host_name (void);
const gchar* g_get_home_dir (void);
const gchar* g_get_tmp_dir (void);
gchar* g_get_current_dir (void);
const gchar* g_basename (const gchar *file_name);
#define g_dirname
gboolean g_path_is_absolute (const gchar *file_name);
const gchar* g_path_skip_root (const gchar *file_name);
gchar* g_path_get_basename (const gchar *file_name);
gchar* g_path_get_dirname (const gchar *file_name);
gchar * g_build_filename (const gchar *first_element,
...);
gchar * g_build_filenamev (gchar **args);
gchar * g_build_path (const gchar *separator,
const gchar *first_element,
...);
gchar * g_build_pathv (const gchar *separator,
gchar **args);
char * g_format_size_for_display (goffset size);

gchar* g_find_program_in_path (const gchar *program);

gint g_bit_nth_lsf (gulong mask,
gint nth_bit);
gint g_bit_nth_msf (gulong mask,
gint nth_bit);
guint g_bit_storage (gulong number);

guint g_spaced_primes_closest (guint num);

void g_atexit (GVoidFunc func);

guint g_parse_debug_string (const gchar *string,
const GDebugKey *keys,
guint nkeys);
GDebugKey;

void (*GVoidFunc) (void);
void (*GFreeFunc) (gpointer data);

void g_qsort_with_data (gconstpointer pbase,
gint total_elems,
gsize size,
GCompareDataFunc compare_func,
gpointer user_data);

void g_nullify_pointer (gpointer *nullify_location);

說明

這些是可移植的實用函式。

細節

g_get_application_name ()

const gchar*        g_get_application_name              (void);

取得應用程式人們可讀取的名稱,這名稱是由g_set_application_name()設定,如果可以的話這個名稱應該是區域性的,且用來顯示給使用者的,與g_get_prgname()相比,這個函式取得非區域性的名稱,假如g_set_application_name() 沒有被呼叫,傳回g_get_prgname() 的結果(如果g_set_prgname()也沒有被呼叫那就會是NULL)。

傳回:

人們可讀取的應用程式名稱,可能傳回NULL

2.2版以後使用


g_set_application_name ()

void                g_set_application_name              (const gchar *application_name);

設定應用程式名稱為人們可讀取的,如果可能的話這個名稱應該是區域性的,並且用來顯示給使用者看,與g_set_prgname()相比,這是用來設定非區域性的名稱,g_set_prgname() 會自動由 gtk_init()呼叫,但是 g_set_application_name() 不會。

注意因為執行緒安全的考量,這個函式只能被呼叫一次。

應用程式名稱用於像是錯誤訊息的內容,或是在工作列顯示應用程式的名稱。

應用程式:

應用程式的區域性名稱

2.2以後


g_get_prgname ()

gchar*              g_get_prgname                       (void);

取得程式的名稱,與 g_get_application_name()相比這程式不應該是區域性的。(假如你使用GDK或GTK+ 程式名稱是由gdk_init()設定,這個函式是由gtk_init()呼叫,程式名稱藉由argv[0]的最後一個部份來發現)

傳回:

程式的名稱,傳回的字串屬於GLib而且不能修改或釋放。

g_set_prgname ()

void                g_set_prgname                       (const gchar *prgname);

設定程式名稱,與 g_set_application_name()這名稱不應是區域性的,注意基於執行緒安全性考量這函式只能被呼叫一次。

prgname :

程式的名稱。

g_getenv ()

const gchar*        g_getenv                            (const gchar *variable);

傳回環境變數的值,名稱跟值是用GLib檔案名稱編碼,在UNIX上,這意味著實際的字元可能或不可能是某些一致的字元集和編碼,在Windows上,是UTF-8編碼,在Windows上,如果環境變數的值包含參考其他的環境變數,他們就會展開。

變數::

環境變數的取得是以GLib檔案名稱編碼。

傳回:

環境變數的值,或是假如環境變數沒有找到就傳回NULL,傳回的字串會被接下來的g_getenv()g_setenv()g_unsetenv() 呼叫所覆蓋。

g_setenv ()

gboolean            g_setenv                            (const gchar *variable,
const gchar *value,
gboolean overwrite);

設定一個環境變數,變數的名稱跟值是以GLib檔案名稱來編碼,在UNIX上,這意味著它們是任意的序列字元,在Windows上,應該是以UTF-8編碼。

注意在某些系統上,當變數被覆寫,前一個變數跟它的值所使用的記憶體不會被回收。

變數:

環境變數的設定,必須不包含'='。

值:

設定變數的值。

複寫:

假如變數已存在是否改變變數。

傳回:

假如環境變數沒有被設定傳回FALSE

2.4版以後才有


g_unsetenv ()

void                g_unsetenv                          (const gchar *variable);

移除環境變數。

注意在某些系統上,當變數被覆寫時,前一個變數跟值所使用的記憶體不能被回收,此外,這個函式不保證在執行緒安全模式下操作。

變數:

環境變數的移除不能魽有'='。

2.4版以後使用。


g_listenv ()

gchar**             g_listenv                           (void);

取得所有環境變數的名稱

傳回:

必須是 g_strfreev()釋放的一個以NULL-結尾的字串列表,要移植到Windows的程式通常使用這個函式跟g_getenv() 而不是直接使用C函式庫的environ陣列,在Windows上,在wnviron陣列中的字串是以系統代碼夜來編碼,而在最典型的使用案例中對於使用GLib程式的環境變數你會想要使用這個函式跟g_getenv() 提供的UTF-8編碼。

2.8以後使用


g_get_user_name ()

const gchar*        g_get_user_name                     (void);

取得目前使用者的名稱,傳回字串的編碼是系統定義的,在UNIX上,可能是首選的檔案名稱編碼,或是其他的,這甚至在一致的機器上也不能保證,在Windows上,它總是使用UTF-8。

傳回:

目前的使用者名稱。

g_get_real_name ()

const gchar*        g_get_real_name                     (void);

取得使用者的真實名稱,這個名稱通常來自passwd檔的使用者紀錄,傳回字串的編碼是系統定義的,(然而在Windows上一定是使用UTF-8),假如真實的使用者名稱沒有定義,會傳回"Unknown"字串。

傳回:

使用者的真實名稱。

g_get_user_cache_dir ()

const gchar*        g_get_user_cache_dir                (void);

傳回儲存特定使用者非必要的暫存資料所在的基本目錄。

在UNIX平台上,使用 XDG基本目錄規範 來定義。

傳回:

GLib所擁有的字串不能被修改或釋放。

2.6以後使用


g_get_user_data_dir ()

const gchar*        g_get_user_data_dir                 (void);

傳回像是特定使用者所自訂的圖示等的應用程式資料所在的基本目錄。

在UNIX平台上使用 XDG Base Directory Specification規範定義。

傳回:

GLib的字串不可修改或釋放。

2.6版後使用


g_get_user_config_dir ()

const gchar*        g_get_user_config_dir               (void);

傳回儲存使用者特定的應用程式的組態資訊像是使用者的偏好設定之類的基本目錄。

在UNIX平台上使用 XDG 基本目錄規範 來定義。 

傳回:

GLib的字串不可修改或釋放。

Since 2.6


enum GUserDirectory

typedef enum {
G_USER_DIRECTORY_DESKTOP,
G_USER_DIRECTORY_DOCUMENTS,
G_USER_DIRECTORY_DOWNLOAD,
G_USER_DIRECTORY_MUSIC,
G_USER_DIRECTORY_PICTURES,
G_USER_DIRECTORY_PUBLIC_SHARE,
G_USER_DIRECTORY_TEMPLATES,
G_USER_DIRECTORY_VIDEOS,

G_USER_N_DIRECTORIES
} GUserDirectory;

These are logical ids for special directories which are defined depending on the platform used. You should use g_get_user_special_dir() to retrieve the full path associated to the logical id.

The GUserDirectory enumeration can be extended at later date. Not every platform has a directory for every logical id in this enumeration.

G_USER_DIRECTORY_DESKTOP

the user's Desktop directory

G_USER_DIRECTORY_DOCUMENTS

the user's Documents directory

G_USER_DIRECTORY_DOWNLOAD

the user's Downloads directory

G_USER_DIRECTORY_MUSIC

the user's Music directory

G_USER_DIRECTORY_PICTURES

the user's Pictures directory

G_USER_DIRECTORY_PUBLIC_SHARE

the user's shared directory

G_USER_DIRECTORY_TEMPLATES

the user's Templates directory

G_USER_DIRECTORY_VIDEOS

the user's Movies directory

G_USER_N_DIRECTORIES

the number of enum values

Since 2.14


g_get_user_special_dir ()

const gchar*        g_get_user_special_dir              (GUserDirectory directory);

Returns the full path of a special directory using its logical id.

On Unix this is done using the XDG special user directories. For compatibility with existing practise, G_USER_DIRECTORY_DESKTOP falls back to $HOME/Desktop when XDG special user directories have not been set up.

Depending on the platform, the user might be able to change the path of the special directory without requiring the session to restart; GLib will not reflect any change once the special directories are loaded.

directory :

the logical id of special directory

Returns :

the path to the specified special directory, or NULL if the logical id was not found. The returned string is owned by GLib and should not be modified or freed.

Since 2.14


g_get_system_data_dirs ()

const gchar* const * g_get_system_data_dirs             (void);

Returns an ordered list of base directories in which to access system-wide application data.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification

On Windows the first elements in the list are the Application Data and Documents folders for All Users. (These can be determined only on Windows 2000 or later and are not present in the list on other Windows versions.) See documentation for CSIDL_COMMON_APPDATA and CSIDL_COMMON_DOCUMENTS.

Then follows the "share" subfolder in the installation folder for the package containing the DLL that calls this function, if it can be determined.

Finally the list contains the "share" subfolder in the installation folder for GLib, and in the installation folder for the package the application's .exe file belongs to.

The installation folders above are determined by looking up the folder where the module (DLL or EXE) in question is located. If the folder's name is "bin", its parent is used, otherwise the folder itself.

Note that on Windows the returned list can vary depending on where this function is called.

Returns :

a NULL-terminated array of strings owned by GLib that must not be modified or freed.

Since 2.6


g_get_system_config_dirs ()

const gchar* const * g_get_system_config_dirs           (void);

Returns an ordered list of base directories in which to access system-wide configuration information.

On UNIX platforms this is determined using the mechanisms described in the XDG Base Directory Specification

Returns :

a NULL-terminated array of strings owned by GLib that must not be modified or freed.

Since 2.6


g_reload_user_special_dirs_cache ()

void                g_reload_user_special_dirs_cache    (void);

Resets the cache used for g_get_user_special_dir(), so that the latest on-disk version is used. Call this only if you just changed the data on disk yourself.

Due to threadsafety issues this may cause leaking of strings that were previously returned from g_get_user_special_dir() that can't be freed. We ensure to only leak the data for the directories that actually changed value though.

Since 2.22


g_get_host_name ()

const gchar*        g_get_host_name                     (void);

Return a name for the machine.

The returned name is not necessarily a fully-qualified domain name, or even present in DNS or some other name service at all. It need not even be unique on your local network or site, but usually it is. Callers should not rely on the return value having any specific properties like uniqueness for security purposes. Even if the name of the machine is changed while an application is running, the return value from this function does not change. The returned string is owned by GLib and should not be modified or freed. If no name can be determined, a default fixed string "localhost" is returned.

Returns :

the host name of the machine.

Since 2.8


g_get_home_dir ()

const gchar*        g_get_home_dir                      (void);

取得定義在password資料庫中的使用者根目錄。

注意對照於傳統的UNIX工具,這個函式較喜歡passwd紀錄的HOME環境變數

這樣決定的一個理由就是再很多情況下應用程式需要特殊處理來處理HOME在下面的情況:

Not owned by the user
Not writeable
Not even readable

由於應用程式一般不能寫入來處理這些情況,所以不要用 g_get_home_dir()來關注HOME是較好的,而且可以傳回真正的使用者根目錄,假如應用程式要專注HOME,他們可以這樣寫:

1
2
3
const char *homedir = g_getenv ("HOME");
if (!homedir)
homedir = g_get_home_dir ();

Returns :

使用者的根目錄

g_get_tmp_dir ()

const gchar*        g_get_tmp_dir                       (void);

Gets the directory to use for temporary files. This is found from inspecting the environment variables TMPDIR, TMP, and TEMP in that order. If none of those are defined "/tmp" is returned on UNIX and "C:\" on Windows. The encoding of the returned string is system-defined. On Windows, it is always UTF-8. The return value is never NULL.

Returns :

the directory to use for temporary files.

g_get_current_dir ()

gchar*              g_get_current_dir                   (void);

Gets the current directory. The returned string should be freed when no longer needed. The encoding of the returned string is system defined. On Windows, it is always UTF-8.

Returns :

the current directory.

g_basename ()

const gchar*        g_basename                          (const gchar *file_name);

Warning

g_basename has been deprecated since version 2.2 and should not be used in newly-written code. Use g_path_get_basename() instead, but notice that g_path_get_basename() allocates new memory for the returned string, unlike this function which returns a pointer into the argument.

Gets the name of the file without any leading directory components. It returns a pointer into the given file name string.

file_name :

the name of the file.

Returns :

the name of the file without any leading directory components.

g_dirname

#define             g_dirname

Warning

g_dirname is deprecated and should not be used in newly-written code.

This function is deprecated and will be removed in the next major release of GLib. Use g_path_get_dirname() instead.

Gets the directory components of a file name. If the file name has no directory components "." is returned. The returned string should be freed when no longer needed.

Returns :

the directory components of the file.

g_path_is_absolute ()

gboolean            g_path_is_absolute                  (const gchar *file_name);

Returns TRUE if the given file_name is an absolute file name, i.e. it contains a full path from the root directory such as "/usr/local" on UNIX or "C:\windows" on Windows systems.

file_name :

a file name.

Returns :

TRUE if file_name is an absolute path.

g_path_skip_root ()

const gchar*        g_path_skip_root                    (const gchar *file_name);

Returns a pointer into file_name after the root component, i.e. after the "/" in UNIX or "C:\" under Windows. If file_name is not an absolute path it returns NULL.

file_name :

a file name.

傳回:

a pointer into file_name after the root component.

g_path_get_basename ()

gchar*              g_path_get_basename                 (const gchar *file_name);

Gets the last component of the filename. If file_name ends with a directory separator it gets the component before the last slash. If file_name consists only of directory separators (and on Windows, possibly a drive letter), a single separator is returned. If file_name is empty, it gets ".".

file_name :

檔案的名稱。

Returns :

a newly allocated string containing the last component of the filename.

g_path_get_dirname ()

gchar*              g_path_get_dirname                  (const gchar *file_name);

取得檔案名稱的目錄部份,假如檔案名稱沒有目錄的部份會傳回 ".",這個傳回的字串不再使用時會釋放出來。

file_name :

檔案的名稱。

傳回::

檔案的目錄部份。

g_build_filename ()

gchar *             g_build_filename                    (const gchar *first_element,
...);

從一系列正確使用分隔符號的檔名元素來建構一個檔案名稱。

在Unix上,這個函式跟g_build_path (G_DIR_SEPARATOR_S, first_element, ....)作用一樣。

在Windows上,它會考慮到要用反斜線 (\ 或是斜線 (/) 來作為檔名的分隔符號,但是在Unix則是一致,當檔案的路徑名稱分隔符號需要插入時,先前出現在參數最後一個分隔符 (由左到右這樣讀)會使用。

不要嘗試強迫結果的檔名會是絕對路徑,假如第一個元素事相對路徑,結果也會是有相對路徑。

first_element :

the first element in the path

... :

remaining elements in path, terminated by NULL

Returns :

a newly-allocated string that must be freed with g_free().

g_build_filenamev ()

gchar *             g_build_filenamev                   (gchar **args);

Behaves exactly like g_build_filename(), but takes the path elements as a string array, instead of varargs. This function is mainly meant for language bindings.

args :

NULL-terminated array of strings containing the path elements.

Returns :

a newly-allocated string that must be freed with g_free().

Since 2.8


g_build_path ()

gchar *             g_build_path                        (const gchar *separator,
const gchar *first_element,
...);

Creates a path from a series of elements using separator as the separator between elements. At the boundary between two elements, any trailing occurrences of separator in the first element, or leading occurrences of separator in the second element are removed and exactly one copy of the separator is inserted.

Empty elements are ignored.

The number of leading copies of the separator on the result is the same as the number of leading copies of the separator on the first non-empty element.

The number of trailing copies of the separator on the result is the same as the number of trailing copies of the separator on the last non-empty element. (Determination of the number of trailing copies is done without stripping leading copies, so if the separator is ABA, ABABA has 1 trailing copy.)

However, if there is only a single non-empty element, and there are no characters in that element not part of the leading or trailing separators, then the result is exactly the original value of that element.

Other than for determination of the number of leading and trailing copies of the separator, elements consisting only of copies of the separator are ignored.

separator :

a string used to separator the elements of the path.

first_element :

the first element in the path

... :

remaining elements in path, terminated by NULL

Returns :

a newly-allocated string that must be freed with g_free().

g_build_pathv ()

gchar *             g_build_pathv                       (const gchar *separator,
gchar **args);

Behaves exactly like g_build_path(), but takes the path elements as a string array, instead of varargs. This function is mainly meant for language bindings.

separator :

a string used to separator the elements of the path.

args :

NULL-terminated array of strings containing the path elements.

Returns :

a newly-allocated string that must be freed with g_free().

Since 2.8


g_format_size_for_display ()

char *              g_format_size_for_display           (goffset size);

Formats a size (for example the size of a file) into a human readable string. Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed rounded to the nearest tenth. E.g. the file size 3292528 bytes will be converted into the string "3.1 MB".

The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).

This string should be freed with g_free() when not needed any longer.

size :

a size in bytes.

Returns :

a newly-allocated formatted string containing a human readable file size.

Since 2.16


g_find_program_in_path ()

gchar*              g_find_program_in_path              (const gchar *program);

Locates the first executable named program in the user's path, in the same way that execvp() would locate it. Returns an allocated string with the absolute path name, or NULL if the program is not found in the path. If program is already an absolute path, returns a copy of program if program exists and is executable, and NULL otherwise. On Windows, if program does not have a file type suffix, tries with the suffixes .exe, .cmd, .bat and .com, and the suffixes in the PATHEXT environment variable.

On Windows, it looks for the file in the same way as CreateProcess() would. This means first in the directory where the executing program was loaded from, then in the current directory, then in the Windows 32-bit system directory, then in the Windows directory, and finally in the directories in the PATH environment variable. If the program is found, the return value contains the full name including the type suffix.

program :

a program name in the GLib file name encoding

Returns :

absolute path, or NULL

g_bit_nth_lsf ()

gint                g_bit_nth_lsf                       (gulong mask,
gint nth_bit);

Find the position of the first bit set in mask, searching from (but not including) nth_bit upwards. Bits are numbered from 0 (least significant) to sizeof(gulong) * 8 - 1 (31 or 63, usually). To start searching from the 0th bit, set nth_bit to -1.

mask :

a gulong containing flags.

nth_bit :

the index of the bit to start the search from.

Returns :

the index of the first bit set which is higher than nth_bit.

g_bit_nth_msf ()

gint                g_bit_nth_msf                       (gulong mask,
gint nth_bit);

Find the position of the first bit set in mask, searching from (but not including) nth_bit downwards. Bits are numbered from 0 (least significant) to sizeof(gulong) * 8 - 1 (31 or 63, usually). To start searching from the last bit, set nth_bit to -1 or GLIB_SIZEOF_LONG * 8.

mask :

a gulong containing flags.

nth_bit :

the index of the bit to start the search from.

Returns :

the index of the first bit set which is lower than nth_bit.

g_bit_storage ()

guint               g_bit_storage                       (gulong number);

Gets the number of bits used to hold number, e.g. if number is 4, 3 bits are needed.

number :

a guint.

Returns :

the number of bits used to hold number.

g_spaced_primes_closest ()

guint               g_spaced_primes_closest             (guint num);

Gets the smallest prime number from a built-in array of primes which is larger than num. This is used within GLib to calculate the optimum size of a GHashTable.

The built-in array of primes ranges from 11 to 13845163 such that each prime is approximately 1.5-2 times the previous prime.

num :

a guint.

Returns :

the smallest prime number from a built-in array of primes which is larger than num.

g_atexit ()

void                g_atexit                            (GVoidFunc func);

Specifies a function to be called at normal program termination.

Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor macro that maps to a call to the atexit() function in the C library. This means that in case the code that calls g_atexit(), i.e. atexit(), is in a DLL, the function will be called when the DLL is detached from the program. This typically makes more sense than that the function is called when the GLib DLL is detached, which happened earlier when g_atexit() was a function in the GLib DLL.

The behaviour of atexit() in the context of dynamically loaded modules is not formally specified and varies wildly.

On POSIX systems, calling g_atexit() (or atexit()) in a dynamically loaded module which is unloaded before the program terminates might well cause a crash at program exit.

Some POSIX systems implement atexit() like Windows, and have each dynamically loaded module maintain an own atexit chain that is called when the module is unloaded.

On other POSIX systems, before a dynamically loaded module is unloaded, the registered atexit functions (if any) residing in that module are called, regardless where the code that registered them resided. This is presumably the most robust approach.

As can be seen from the above, for portability it's best to avoid calling g_atexit() (or atexit()) except in the main executable of a program.

func :

the function to call on normal program termination.

g_parse_debug_string ()

guint               g_parse_debug_string                (const gchar *string,
const GDebugKey *keys,
guint nkeys);

Parses a string containing debugging options into a guint containing bit flags. This is used within GDK and GTK+ to parse the debug options passed on the command line or through environment variables.

If string is equal to "all", all flags are set. If string is equal to "help", all the available keys in keys are printed out to standard error.

string :

a list of debug options separated by colons, spaces, or commas, or NULL.

keys :

pointer to an array of GDebugKey which associate strings with bit flags.

nkeys :

the number of GDebugKeys in the array.

Returns :

the combined set of bit flags.

GDebugKey

typedef struct {
const gchar *key;
guint value;
} GDebugKey;

Associates a string with a bit flag. Used in g_parse_debug_string().

const gchar *key;

the string

guint value;

the flag

GVoidFunc ()

void                (*GVoidFunc)                        (void);

Declares a type of function which takes no arguments and has no return value. It is used to specify the type function passed to g_atexit().


GFreeFunc ()

void                (*GFreeFunc)                        (gpointer data);

Declares a type of function which takes an arbitrary data pointer argument and has no return value. It is not currently used in GLib or GTK+.

data :

a data pointer.

g_qsort_with_data ()

void                g_qsort_with_data                   (gconstpointer pbase,
gint total_elems,
gsize size,
GCompareDataFunc compare_func,
gpointer user_data);

This is just like the standard C qsort() function, but the comparison routine accepts a user data argument.

pbase :

start of array to sort

total_elems :

elements in the array

size :

size of each element

compare_func :

function to compare elements

user_data :

data to pass to compare_func

g_nullify_pointer ()

void                g_nullify_pointer                   (gpointer *nullify_location);

Set the pointer at the specified location to NULL.

nullify_location :

the memory address of the pointer.

Trackback URL for this post:

http://achi.idv.tw/trackback/2339