使用 GFile 异步复制文件并显示进度

源代码

/* gfile-copy.c
 * Heiher 
 */

#include 
#include 

static gboolean timeout_handler(gpointer user_data)
{
	gtk_main_quit();

	return FALSE;
}

static void g_file_copy_progress_handler(goffset current_num_bytes,
			goffset total_num_bytes, gpointer user_data)
{
	GtkProgressBar *progress_bar = GTK_PROGRESS_BAR(user_data);
	gchar buf[1024] = { 0 };

	g_sprintf(buf, "%ld KB / %ld KB", current_num_bytes / 1024,
				total_num_bytes / 1024);
	gtk_progress_bar_set_text(progress_bar, buf);
	gtk_progress_bar_set_fraction(progress_bar, (gdouble)current_num_bytes / (gdouble)total_num_bytes);
}

static void g_file_copy_async_ready_handler(GObject *source_object,
			GAsyncResult *res, gpointer user_data)
{
	GtkProgressBar *progress_bar = GTK_PROGRESS_BAR(user_data);

	g_file_copy_finish(G_FILE(source_object), res, NULL);
	gtk_progress_bar_set_text(progress_bar, "Finished");
	gtk_progress_bar_set_fraction(progress_bar, 1.0);

	g_timeout_add_seconds(2, timeout_handler, NULL);
}

int main(int argc, char *argv[])
{
	GtkWidget *window = NULL;
	GtkWidget *progress_bar = NULL;
	GFile *src = NULL, *dst = NULL;

	gtk_init(&argc, &argv);

	window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	gtk_widget_set_size_request(window, 400, 30);
	gtk_widget_show(window);

	progress_bar = gtk_progress_bar_new();
	gtk_container_add(GTK_CONTAINER(window),
				progress_bar);
	gtk_widget_show(progress_bar);

	src = g_file_new_for_path("/tmp/src.img");
	dst = g_file_new_for_path("/tmp/dst.img");

	g_file_copy_async(src, dst, G_FILE_COPY_OVERWRITE,
				G_PRIORITY_DEFAULT, NULL, g_file_copy_progress_handler,
				progress_bar, g_file_copy_async_ready_handler, progress_bar);

	gtk_main();

	return 0;
}

编译、执行

gcc -o gfile-copy gfile-copy.c `pkg-config --cflags --libs gtk+-2.0 gio-2.0`
./gfile-copy

Over!

2 thoughts on “使用 GFile 异步复制文件并显示进度”

Leave a Reply

Your email address will not be published.