如何使用 Glib (C) 写入文件?

How do I write to a file using 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;
    }
}

这是我解决问题的方法! 写入和读取文件

    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;
    }