GNOME Bugzilla – Bug 524686
g_file_replace() does not replace file contents
Last modified: 2008-03-31 07:42:04 UTC
This test case shows that I can't replace a file's contents by using g_file_replace() and writing to the resulting stream. Maybe I am misunderstanding something about the API. Run the example twice. The first time it creates the contents and the second time it tries to change it. For me the contents never change from the original contents.
Created attachment 108123 [details] gfilereplace_test.c
Created attachment 108162 [details] Correct version of the program. Murray, you have to call g_object_unref (stream) before leaving main(). Seems file replacement is done as atomic operation in the streams dispose() or finalize() handler. Will have a look and update the API docs with that information.
Hmm: * This will try to replace the file in the safest way possible so * that any errors during the writing will not affect an already * existing copy of the file. For instance, for local files it * may write to a temporary file and then atomically rename over * the destination when the stream is closed. "when the stream is closed". Also it is obvious that you have to take care to unref your local GObject instances, before leaving functions. Also this behavious is not different from buffered FILE API or streaming API in Java or C#: You have no guaranty that your contents reaches disk, before you close the FILE/stream. Closing this bug.
You don't strictly have to unref the stream. But you must close it (which is done automatically on object finalization if not done before). For e.g. a GC:ed language i expect the app to call close instead of relying on finalization. In C its a tossup which one is best.
Sorry. I didn't see that documentation about closing the stream. Maybe we have a ref leak in giomm (where I first saw this). I'll investigate. Thanks.
Yes, we were doing an extra ref on the result of g_file_replace(). By the way, I'm reviewing our other Gio::File methods too. For some of them I can guess that gio returns a new instance (hence with an initial reference). For others it's not at all clear - for instance, g_file_set_display_name(). It would be nice if someone added the need (or not) to ref the returned object to the documentations for the g_file_* functions.
All objects returned from g_file_* have an initial ref that needs to be unrefed when you're done with it.