我正在Anjuta的Ubuntu 12.04上用C和GTK编写一个程序。它是nbc(Lego NXT编译器)的图形界面。我有一个GTKTextView。现在我想将textview的内容保存到一个文件中,该文件可以由GTKFileChooser选择。现在我不知道如何从TextView获取文本并将其写入文件。我该怎么做?
答案 0 :(得分:5)
首先,使用GtkTextBuffer
从GtkTextView
获取gtk_text_view_get_buffer()
。然后从缓冲区获取开始和结束 GtkTextIters 以用于获取缓冲区的文本。最后,使用您选择的API将该文本写入文件,但是,我建议Gio
。这是我旧教程的片段:
gtk_widget_set_sensitive (text_view, FALSE);
buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (editor->text_view));
gtk_text_buffer_get_start_iter (buffer, &start);
gtk_text_buffer_get_end_iter (buffer, &end);
text = gtk_text_buffer_get_text (buffer, &start, &end, FALSE);
gtk_text_buffer_set_modified (buffer, FALSE);
gtk_widget_set_sensitive (editor->text_view, TRUE);
/* set the contents of the file to the text from the buffer */
if (filename != NULL)
result = g_file_set_contents (filename, text, -1, &err);
else
result = g_file_set_contents (editor->filename, text, -1, &err);
if (result == FALSE)
{
/* error saving file, show message to user */
error_message (err->message);
g_error_free (err);
}
g_free (text);
查看以下API文档:
答案 1 :(得分:1)
void on_toolbutton3_clicked(GtkToolButton *toolbutton, gpointer data)
{
GtkWidget *dialog;
dialog = gtk_file_chooser_dialog_new ("Abspeichern...",
NULL,
GTK_FILE_CHOOSER_ACTION_SAVE,
GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
NULL);
if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT)
{
char *filename;
char *text;
GtkTextIter *start;
GtkTextIter *end;
gboolean result;
GError *err;
filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
gtk_widget_set_sensitive (data, FALSE);
savebuffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (data));
gtk_text_buffer_get_start_iter (savebuffer, &start);
gtk_text_buffer_get_end_iter (savebuffer, &end);
text = gtk_text_buffer_get_text (savebuffer, &start, &end, FALSE);
gtk_text_buffer_set_modified (savebuffer, FALSE);
gtk_widget_set_sensitive (data, TRUE);
/* set the contents of the file to the text from the buffer */
if (filename != NULL)
result = g_file_set_contents (filename, text, -1, &err);
else
result = g_file_set_contents (filename, text, -1, &err);
if (result == FALSE)
{
/* error saving file, show message to user */
}
g_free (text);
}
gtk_widget_destroy (dialog);
}
textview1上的数据点。