Check out the new USENIX Web site. next up previous
Next: Asynchronous API Up: Synchronous API Previous: The GnomeVFSHandle object

Synchronous I/O Example

Here is a simple example demonstrating synchronous operation in GNOME VFS. This subroutine will read a file and output its contents to stdout. The code should be rather self-explanatory.

gboolean vfs_cat (const char *uri)
{
  GnomeVFSURI *vfs_uri;
  GnomeVFSHandle *handle;
  GnomeVFSResult result;

  vfs_uri = gnome_vfs_uri_new (uri);
  if (vfs_uri == NULL) {
    printf ("`%s' is not a valid URI.\n",
      uri);
    return FALSE;
  }

  result = gnome_vfs_open_uri
    (&handle, vfs_uri, GNOME_VFS_OPEN_READ);

  if (result != GNOME_VFS_OK) {
    printf ("Error opening `%s': %s\n",
      uri,
      gnome_vfs_result_to_string (result));
    return FALSE;
  }

  while (1) {
    GnomeVFSFileSize bytes_read;
    GnomeVFSFileSize i;
    char buffer[4096];

    result = gnome_vfs_read
      (handle,
       buffer,
       sizeof (buffer),
       &bytes_read);
    if (result != GNOME_VFS_OK) {
      printf ("%s: %s\n", uri,
        gnome_vfs_result_to_string
          (result));
      return FALSE;
    }

    if (bytes_read == 0)
      break;
    for (i = 0; i < bytes_read; i++)
      putchar (buffer[i]);
  }

  gnome_vfs_close (handle);
  gnome_vfs_uri_unref (vfs_uri);
  return TRUE;
}



Ettore Perazzoli 2000-04-26