Search code examples
cgtkglade

GTK - Cannot print buffer value using function `printf`


I get the contents of my textview and I want to display the contents in the terminal using the printf function. But have stange symbols (Why?):

enter image description here

// get textbuffer from textview end print value in terminal
void on_lower_button_clicked(GtkWidget *lower_button, GtkTextView *textview_1)
{
    GtkTextBuffer *textbuffer_1;
    textbuffer_1 = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview_1));
    printf("%s\n", textbuffer_1); // strange symbols from my buffer ...
}

int main(int argc, char *argv[])
{
  GtkWidget *lower_button;
  GtkBuilder *builder;
  GtkWidget *window;
  GError *error = NULL;

  gtk_init(&argc, &argv);

  builder = gtk_builder_new();
  if(!gtk_builder_add_from_file(builder, "template.ui", &error)) {
    g_printerr("Error loading file: %s\n", error->message);
    g_clear_error(&error);
    return 1;
  }

  window = GTK_WIDGET(gtk_builder_get_object(builder, "window"));
  lower_button = GTK_WIDGET(gtk_builder_get_object(builder, "lower_button"));

  gtk_builder_connect_signals(builder, NULL);
  // when I click on the button (lower_button) call 
  // on_lower_button_clicked function and transferred to her textview_1
  g_object_unref(G_OBJECT(builder));

  gtk_widget_show(window);
  gtk_main();

  return 0;
}

Solution

  • GtkTextBuffer is not a character array, it is a GTK object that can not be simply printed as text.

    You need to extract the text from it if you want to print it or write it to file.

    To do this, you will need to get a couple of GtkTextIter objects, and then use gtk_text_buffer_get_text.

    Note, that if you have non English characters in your text, you may still have issues using printf, because the resulting text is UTF-8 encoded.

    Here is an example code:

    GtkTextIter start, end;
    gchar *text;
    
    gtk_text_buffer_get_start_iter(textview_1, &start);
    gtk_text_buffer_get_end_iter(textview_1, &end);
    
    text = gtk_text_buffer_get_text(textview_1, &start, &end, FALSE);
    
    printf("%s\n",text);
    
    g_free(text); //you need to clean up this buffer!