在 基本檔案讀寫 中使用g_file_get_contents()、g_file_set_contents()函式,會對檔案作
整個讀取與整個寫入的動作,若您想要對檔案作一些逐字元、逐行讀取、附加等操作,則可以使用GIOChannel。
下面這個程式改寫 基本檔案讀寫 中的範例,使用GIOChannel來進行檔案讀寫的動作:
#include <glib.h>
handle_error(GError *error) { if(error != NULL) { g_printf(error->message); g_clear_error(&error); } }
int main(int argc, char *argv[]) { gchar *src, *dest; GIOChannel *ioChannel; gchar *content; gsize length; GError *error = NULL; if(argc >= 3) { src = argv[1]; dest = argv[2]; } else { return 1; } if (!g_file_test(src, G_FILE_TEST_EXISTS)) { g_error("Error: File does not exist!"); }
ioChannel = g_io_channel_new_file(src, "r", &error); handle_error(error); g_io_channel_read_to_end(ioChannel, &content, &length, NULL); g_io_channel_close(ioChannel); ioChannel = g_io_channel_new_file(dest, "w", &error); handle_error(error); g_io_channel_write_chars(ioChannel, content, -1, &length, NULL); g_io_channel_close(ioChannel); g_free(content); return 0; }
您使用的是g_io_channel_new_file()函式來建立GIOChannel,建立時可以使用"r"、"w"、"a"、"r+"、"w+"、"a+"等檔案模式,其作用與使用 fopen() 時的模式相同。
程式中使用的是g_io_channel_read_to_end()函式,一次讀取所有的檔案內容,您也可以使用
g_io_channel_read_chars()、g_io_channel_read_line()、
g_io_channel_read_line_string()等函式,來對檔案作不同的讀取動作。
|
|