Mike's Musings

Do you want code with that mongoose?

0

Reading and Writing files with GIOmm

Seeing as a while ago I posted on reading a file in with GnomeVFSmm since now and then the folks at GNOME have release GIO their new i/o library.  Thankfully this makes life for the developer a lot easier from what I can tell to prove this here is my example from my GnomeVFSmm reworked to use GIO.

Reading from a file:

Glib::ustring read_from_file(Glib::ustring file_name)
{
	Glib::RefPtr fp = Gio::File::create_for_uri(file_name);

	char *raw;
	gsize read_bytes;
	std::string e_tag;

	fp->load_contents(raw, read_bytes, e_tag);

	Glib::ustring buffer = raw;
	return buffer;
}

Writing to a file:

void write_to_file(Glib::ustring file_name, std::string e_tag, Glib::ustring buf)
{
	Glib::RefPtr fp = Gio::File::create_for_uri(file_name);
	fp->replace_contents(buf.c_str(), e_tag, e_tag);
}

Just as a note this method only works for reading and writing text files, and there should be some error checking which has been omitted.  If there is any problems in the above code do not hesitate to let me know.  Also as a side note does anyone know how to retrieve the mime type for a file using GIOmm.

Leave a Reply