Retrieve text buffer size in bytes

Hi there.
The question is how can I get the size in bytes of text buffer to save it later in the file?
I searched for appropriate function in docs but didn’t find exactly what I need.
I can get offset of last char with


but it will be the number of UTF-8 symbols and some of them will be bigger then 1 byte.
So, how can I do it?

THis older example may still work:

Or you may investigate the source code of GEdit.

As I understood, there is no native function to do this. But I did this function for myself (thanks stack overflow).
Here is code:

gtk_text_buffer_get_size (GtkTextBuffer * buff)
  GtkTextIter iter;
  gtk_text_buffer_get_start_iter(buff, &iter);
  gint bytecount = 0;
    bytecount += gtk_text_iter_get_bytes_in_line(&iter);
  } while(gtk_text_iter_forward_line(&iter));

  return bytecount;

Thus, question is answered and we can discuss, why there is no such function?

Because getting the length of the buffer in bytes can be trivially open coded as:

GtkTextIter start, end;

gtk_text_buffer_get_bounds (buffer, &start, &end);

g_autofree char *foo = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);

return strlen (foo);

Since you’re already saving the buffer contents, you’re already getting the text. The length in bytes is not really useful for anything except for storing the buffer data into some bytes buffer, like a file.

On the other hand, the length in characters is a bit more complicated to retrieve, especially if we don’t want to expose the internals of the text buffer object, which warrants the presence of a specialised getter function.


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