Write GBytes * to a file

Hi everyone
This is new for me. I’ve download a file with libsoup. It’s a GBytes * pointer and I want to write (apng file) to a file.
How can I do this ?
Thanks !

Create a GFile instance for the path you wish to use, and then call g_file_replace_contents_bytes_async() with the bytes buffer and the callback for when the operation terminates:

static void
on_replace_complete (GObject *source,
                     GAsyncResult *result,
                     gpointer data G_GNUC_UNUSED)
{
  g_autoptr (GError) error = NULL;

  g_file_replace_contents_finish (G_FILE (source), result, NULL, &error);
  if (error != NULL)
    g_warning ("Unable to replace contents: %s", error->message);
}

static void
save_bytes (const char *path,
            GBytes *data)
{
  g_autoptr (GFile) file = g_file_new_for_path (path);
  g_file_replace_contents_bytes_async (file, data,
                                       NULL,
                                       FALSE,
                                       G_FILE_CREATE_NONE,
                                       NULL,
                                       on_replace_complete,
                                       NULL);
}

The code above is untested, and assumes you already have a main loop running; if you don’t, you will need to create a GMainLoop instance, pass it as use data to g_file_replace_contents_bytes_async(); you can call g_main_loop_run() after that, and call g_main_loop_quit() in the on_replace_complete callback.

Thanks a lot !

It’s a little hard to find this function. I try to find g_file_write_bytes_something…

This topic was automatically closed 45 days after the last reply. New replies are no longer allowed.