Re: writing to a buffer: help



Hello,

Le 30/01/2013, Rudra Banerjee <rudra banerjee aol co uk> a Ãcrit :
My second question in this is that,
I have created a buffer from a file in a different function as

  char* buffer;
  gsize length;
  GError* error=NULL; 
  filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
  g_file_get_contents(filename, &buffer, &length , &error);

I have not "g_free"-d it. Can I use the same buffer to if I want to
append the buffer from update_file.c? Or should I g_free that buffer
and reopen it?
I think you miss the point here. Let's detail it further. Calling
g_file_get_contents(filename, &buffer, &length , &error);

is equivalent in essence to:
File *f;
char *buffer;

f = fopen(filename, "r");
buffer = malloc(sizeof(char) * (file length));
do
{
  buffer[i] = fgetc(f);
} while (!EOF);
fclose(f);

Which means that you open the file, copy the content to memory and
close the file. So what you call "buffer" is not related to your file
anymore, it is just an array of char in memory that contains whatever
your file was when it was read.

You can make changes to the content of this array (take care to the
size), they will not be mirrored in the file. This "buffer" is just a
memory array.

Then, you can create a new file (with the same name to overwrite) which
will contains the content of your memory array using
g_file_set_content(). But here again, the two stuffs are not connected.
Your file is opened, write the content of the memory array and close
afterwards. Whatever change you do to the array later will not reflect
in the file.

Is it clearer ?

Damien.



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]