Re: glib outstanding stuff
- From: Joel Becker <jlbec evilplan org>
- To: Havoc Pennington <hp redhat com>
- Cc: gtk-devel-list gnome org
- Subject: Re: glib outstanding stuff
- Date: Thu, 5 Oct 2000 02:13:00 +0100
On Wed, Oct 04, 2000 at 07:04:42PM -0400, Havoc Pennington wrote:
> +gchar*
> +g_file_get_contents (const gchar *filename,
> + GError **error)
> +{
> + FILE *f;
> + gchar buf[1024];
> + size_t bytes;
> + GString *str;
> +
> + g_return_val_if_fail (filename != NULL, NULL);
> +
> + f = fopen (filename, "r");
> +
> + if (f == NULL)
> + {
> + g_set_error (error,
> + G_FILE_ERROR,
> + errno_to_g_file_error (errno),
> + _("Failed to open file '%s': %s"),
> + filename, strerror (errno));
> +
> + return NULL;
> + }
> +
> + str = g_string_new ("");
> +
> + while (!feof (f))
> + {
> + bytes = fread (buf, 1, 1024, f);
> +
> + if (ferror (f))
> + {
> + g_set_error (error,
> + G_FILE_ERROR,
> + errno_to_g_file_error (errno),
> + _("Error reading file '%s': %s"),
> + filename, strerror (errno));
> +
> + g_string_free (str, TRUE);
> +
> + return NULL;
> + }
> +
> + g_string_append_len (str, buf, bytes);
> + }
> +
> + fclose (f);
> +
> + return g_string_free (str, FALSE);
> +}
Pardon my asking, but why didn't you use:
--8<------------------------------------------------------
/* error checking stripped */
fd = open(filename, O_RDONLY);
fstat(fd, &stat_buf);
data = g_new(stat_buf.size + 1);
bytes_read = 0;
while (bytes_read < stat_buf.st_size)
{
rc = read(fd, file_data + bytes_read,
stat_buf.st_size - bytes_read);
if (rc == -1)
{
if (errno != EINTR)
{
error_here();
break;
}
}
else if (rc == 0)
break;
else
bytes_read += rc;
}
file_data[bytes_read] = '\0';
close(fd);
-->8------------------------------------------------------
If the file is too big, the initial g_new() will fail, so there
is no crash. In addition, this saves all the resizings of the g_string.
As we are willing to read as large a chunk as the kernel will give us,
we don't need buffering ala stdio.
This is what I have in my personal convenience libs (modulo
error checking, of course). If there's a good reason for your version,
I'd like to know so I can change. :-)
Joel
--
"Nearly all men can stand adversity, but if you really want to
test a man's character, give him power."
- Abraham Lincoln
http://www.jlbec.org/
jlbec evilplan org
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]