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;
}
}
CodePudding user response:
Here is my way of approaching the problem! To write to a file and to read from it
void write_to_file(const char *name)
{
// Beg of file
FILE *file;
file = fopen(name, "w");
if (file == NULL)
{
printf("error\n");
}
// Write to the file here fputc('c', file);
fclose(file);
}
int read_file(const char *path)
{
GFile *file;
file = g_file_new_for_path(path);
if (file == NULL)
{
g_print("file null\n");
return 1;
}
GBytes *file_bytes = g_file_load_bytes(file, NULL, NULL, NULL);
if (file_bytes == NULL)
{
g_print("bytes null\n");
return 1;
}
size_t data_size = 0;
char *pointer = g_bytes_get_data(file_bytes, &data_size);
if (pointer == NULL)
{
g_print("pointer null\n");
return 1;
}
for (size_t i = 0; i < data_size; i )
{
//Do the reading directly on the pointer to the bytes of the file
}
free(pointer);
g_object_unref(file);
return 0;
}