GTK Gossip: GIOChannel 與 檔案處理

基本檔案讀寫 中使用 g_file_get_contents()、g_file_set_contents()函式,會對檔案作 整個讀取與整個寫入的動作,若您想要對檔案作一些逐字元、逐行讀取、附加等操作,則可以使用GIOChannel。

下面這個程式改寫 
基本檔案讀寫 中的範例,使用GIOChannel來進行檔案讀寫的動作:

  • g_io_channel_demo.c
#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()等函式,來對檔案作不同的讀取動作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值