Reputation: 17
I would like to update a GtkLabel with data imported from a text file, but it doesn't evaluate \n
as a newline character, as it should normally do.
The file contains (for example):
This is a\nnewline.
How do I get this \n
understood by GtkLabel ?
This is my complete code:
#include <gtk/gtk.h>
#include <string.h>
static void
activate (GtkApplication* app,
gpointer user_data)
{
GtkWidget *label, *window;
gchar* test_char;
ssize_t len;
FILE* fh;
window = gtk_application_window_new (app);
gtk_window_set_title (GTK_WINDOW (window), "Test GTK");
gtk_window_set_default_size (GTK_WINDOW (window), 200, 100);
label = gtk_label_new ("");
fh = fopen ("file.txt", "r");
getline (&test_char, &len, fh);
gtk_label_set_text (GTK_LABEL (label), test_char);
gtk_container_add (GTK_CONTAINER (window), label);
gtk_widget_show_all (window);
fclose (fh);
}
int
main (int argc,
char **argv)
{
GtkApplication *app;
int status;
app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
status = g_application_run (G_APPLICATION (app), argc, argv);
g_object_unref (app);
return status;
}
Upvotes: 1
Views: 492
Reputation: 879
The key is converting the literal \n to \n.
There are two ways to do this I can come up with (I leave out the file reading part):
Text in test file:
That's\na\ntest,\nfolks!
1.
gchar *new_txt = g_strcompress (test_char);
gtk_label_set_text (GTK_LABEL (label), new_txt);
g_free (new_txt);
2.
GRegex *regex = g_regex_new ("\\\\n", 0, 0, NULL);
gchar *new_txt = g_regex_replace (regex, test_char, -1, 0, "\\n", 0, NULL);
gtk_label_set_text (GTK_LABEL (label), new_txt);
g_free (new_txt);
g_regex_unref (regex);
Note that you have to escape twice: first for C, then for the regex engine, so that the latter sees: replace \\n with \n. You have to escape both backslashes of \\n for C, that's why you get four backslashes in the string that has to be replaced.
Result for both:
Both ways need a newly-allocated string to store the converted text, so you have to free the memory after usage.
Upvotes: 2