#include <gio/gio.h> #include <glib.h> int main (int argc, char *argv[]) { /* 少写了这个程序就崩溃了 调试了老半天 T_T */ g_type_init (); GFile *file;/* 文件抽象数据类型 */ GOutputStream *fos; /* 用来写的 */ GError *error = NULL; /* 创建file对象 */ file = g_file_new_for_path ("./test_file"); /* 获取输出流 */ fos = G_OUTPUT_STREAM (g_file_replace (file, NULL, FALSE, G_FILE_CREATE_NONE, NULL, &error)); if (!fos) { g_error ("%s", error->message); g_error_free (error); return 1; } /* 写入 */ GString *str = g_string_new ("这些文字将写入 test_file。\n"); g_output_stream_write_all (fos, str->str, str->len, NULL, NULL, NULL); g_output_stream_flush (fos, NULL, NULL); g_string_free (str, TRUE); /* 清理 */ g_output_stream_close (fos, NULL, NULL); g_object_unref (file); return 0; }
#include <gio/gio.h> #include <glib.h> int main (int argc, char *argv[]) { if (argc < 2) return 1; /* 少写了这个程序就崩溃了 调试了老半天 T_T */ g_type_init (); GFile *file;/* 文件抽象数据类型 */ GInputStream *fis; /* 用来读的 */ GError *error = NULL; GDataInputStream *dis; /* 抽象输入流 */ /* 创建file对象 */ file = g_file_new_for_path (argv[1]); /* 获取输入流 */ fis = G_INPUT_STREAM (g_file_read (file, NULL, &error)); if (!fis) { g_error ("%s", error->message); g_error_free (error); return 1; } /* 读取 */ dis = g_data_input_stream_new (fis); char *line; while (TRUE) { line = g_data_input_stream_read_line (dis, NULL, NULL, &error); if (error) { g_error ("%s", error->message); return 1; } if (!line) break; g_print ("%s\n", line); g_free (line); } /* 清理 */ g_input_stream_close (fis, NULL, NULL); g_object_unref (file); return 0; }
效果
$ c89 -o reader reader.c `pkg-config --cflags --libs gio-2.0 glib-2.0` $ c89 -o writer writer.c `pkg-config --cflags --libs gio-2.0 glib-2.0` $ ./writer $ ./reader test_file 这些文字将写入 test_file。 $