如何使用glib(c)写入文件?
我正在尝试使用GLIB将数据保存到文件,但不想写入。它仍然可以创建文件。当它创建文件并试图写入该创建的文件指针时,该程序似乎也崩溃了...
相关代码:
#include "save.h"
#include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>
GFile *save;
GFileIOStream *stream;
void initSave() {
char *home = "", *fmt = "%s/.ProgSave.%d", *saveStr = "";
#ifdef _WIN32
home = getenv("USERPROFILE");
#else
home = getenv("HOME");
#endif
saveStr = g_strdup_printf(fmt, home, 123);
save = g_file_new_for_path(saveStr);
stream = g_file_open_readwrite(save, NULL, NULL);
if (!stream) {
stream = g_file_create_readwrite(save, G_FILE_CREATE_NONE, NULL, NULL);
}
g_free(saveStr);
}
void closeSave() {
g_io_stream_close(G_IO_STREAM(stream), NULL, NULL);
g_object_unref(stream);
g_object_unref(save);
}
void writeWin() {
g_output_stream_write(G_OUTPUT_STREAM(stream), "true", 5, NULL, NULL);
g_output_stream_flush(G_OUTPUT_STREAM(stream), NULL, NULL);
}
bool getWin() {
char line[5];
gsize bytesRead;
g_input_stream_read_all(G_INPUT_STREAM(stream), line, 5, &bytesRead, NULL, NULL);
if (strcmp(line, "true") == 0) {
return true;
} else {
return false;
}
}
I'm trying to save data to a file using glib, but it doesn't want to write. It can still create the file. It also seems when it creates the file, and tries to write to that created file pointer, the program just crashes...
The relevant code:
#include "save.h"
#include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>
GFile *save;
GFileIOStream *stream;
void initSave() {
char *home = "", *fmt = "%s/.ProgSave.%d", *saveStr = "";
#ifdef _WIN32
home = getenv("USERPROFILE");
#else
home = getenv("HOME");
#endif
saveStr = g_strdup_printf(fmt, home, 123);
save = g_file_new_for_path(saveStr);
stream = g_file_open_readwrite(save, NULL, NULL);
if (!stream) {
stream = g_file_create_readwrite(save, G_FILE_CREATE_NONE, NULL, NULL);
}
g_free(saveStr);
}
void closeSave() {
g_io_stream_close(G_IO_STREAM(stream), NULL, NULL);
g_object_unref(stream);
g_object_unref(save);
}
void writeWin() {
g_output_stream_write(G_OUTPUT_STREAM(stream), "true", 5, NULL, NULL);
g_output_stream_flush(G_OUTPUT_STREAM(stream), NULL, NULL);
}
bool getWin() {
char line[5];
gsize bytesRead;
g_input_stream_read_all(G_INPUT_STREAM(stream), line, 5, &bytesRead, NULL, NULL);
if (strcmp(line, "true") == 0) {
return true;
} else {
return false;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是我解决问题的方式!
写入文件并从中读取
Here is my way of approaching the problem!
To write to a file and to read from it