Merge remote-tracking branch 'gvdb/master'
[platform/upstream/glib.git] / glib / gfileutils.c
index 10e5ede..da6cacd 100644 (file)
@@ -19,9 +19,7 @@
  */
 
 #include "config.h"
-
-#include "galias.h"
-#include "glib.h"
+#include "glibconfig.h"
 
 #include <sys/stat.h>
 #ifdef HAVE_UNISTD_H
 #include <stdlib.h>
 
 #ifdef G_OS_WIN32
+#include <windows.h>
 #include <io.h>
-#ifndef F_OK
-#define        F_OK 0
-#define        W_OK 2
-#define        R_OK 4
-#endif /* !F_OK */
-
-#ifndef S_ISREG
-#define S_ISREG(mode) ((mode)&_S_IFREG)
-#endif
-
-#ifndef S_ISDIR
-#define S_ISDIR(mode) ((mode)&_S_IFDIR)
-#endif
-
 #endif /* G_OS_WIN32 */
 
 #ifndef S_ISLNK
 #define O_BINARY 0
 #endif
 
+#include "gfileutils.h"
+
 #include "gstdio.h"
 #include "glibintl.h"
 
+#ifdef HAVE_LINUX_MAGIC_H /* for btrfs check */
+#include <linux/magic.h>
+#include <sys/vfs.h>
+#endif
+
+/**
+ * g_mkdir_with_parents:
+ * @pathname: a pathname in the GLib file name encoding
+ * @mode: permissions to use for newly created directories
+ *
+ * Create a directory if it doesn't already exist. Create intermediate
+ * parent directories as needed, too.
+ *
+ * Returns: 0 if the directory already exists, or was successfully
+ * created. Returns -1 if an error occurred, with errno set.
+ *
+ * Since: 2.8
+ */
+int
+g_mkdir_with_parents (const gchar *pathname,
+                     int          mode)
+{
+  gchar *fn, *p;
+
+  if (pathname == NULL || *pathname == '\0')
+    {
+      errno = EINVAL;
+      return -1;
+    }
+
+  fn = g_strdup (pathname);
+
+  if (g_path_is_absolute (fn))
+    p = (gchar *) g_path_skip_root (fn);
+  else
+    p = fn;
+
+  do
+    {
+      while (*p && !G_IS_DIR_SEPARATOR (*p))
+       p++;
+      
+      if (!*p)
+       p = NULL;
+      else
+       *p = '\0';
+      
+      if (!g_file_test (fn, G_FILE_TEST_EXISTS))
+       {
+         if (g_mkdir (fn, mode) == -1)
+           {
+             int errno_save = errno;
+             g_free (fn);
+             errno = errno_save;
+             return -1;
+           }
+       }
+      else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
+       {
+         g_free (fn);
+         errno = ENOTDIR;
+         return -1;
+       }
+      if (p)
+       {
+         *p++ = G_DIR_SEPARATOR;
+         while (*p && G_IS_DIR_SEPARATOR (*p))
+           p++;
+       }
+    }
+  while (p);
+
+  g_free (fn);
+
+  return 0;
+}
+
 /**
  * g_file_test:
- * @filename: a filename to test
+ * @filename: a filename to test in the GLib file name encoding
  * @test: bitfield of #GFileTest flags
  * 
  * Returns %TRUE if any of the tests in the bitfield @test are
  * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
  *
  * You should never use g_file_test() to test whether it is safe
- * to perform an operaton, because there is always the possibility
+ * to perform an operation, because there is always the possibility
  * of the condition changing before you actually perform the operation.
  * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
- * to know whether it is is safe to write to a file without being
+ * to know whether it is safe to write to a file without being
  * tricked into writing into a different location. It doesn't work!
- *
- * <informalexample><programlisting>
+ * |[
  * /&ast; DON'T DO THIS &ast;/
- *  if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) {
- *    fd = g_open (filename, O_WRONLY);
- *    /&ast; write to fd &ast;/
- *  }
- * </programlisting></informalexample>
+ *  if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) 
+ *    {
+ *      fd = g_open (filename, O_WRONLY);
+ *      /&ast; write to fd &ast;/
+ *    }
+ * ]|
  *
  * Another thing to note is that %G_FILE_TEST_EXISTS and
  * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
  * system call. This usually doesn't matter, but if your program
  * is setuid or setgid it means that these tests will give you
- * the answer for the real user ID and group ID , rather than the
+ * the answer for the real user ID and group ID, rather than the
  * effective user ID and group ID.
  *
+ * On Windows, there are no symlinks, so testing for
+ * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
+ * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
+ * its name indicates that it is executable, checking for well-known
+ * extensions and those listed in the %PATHEXT environment variable.
+ *
  * Return value: whether a test was %TRUE
  **/
 gboolean
@@ -114,98 +184,93 @@ g_file_test (const gchar *filename,
              GFileTest    test)
 {
 #ifdef G_OS_WIN32
-  if (G_WIN32_HAVE_WIDECHAR_API ())
-    {
-      wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
+/* stuff missing in std vc6 api */
+#  ifndef INVALID_FILE_ATTRIBUTES
+#    define INVALID_FILE_ATTRIBUTES -1
+#  endif
+#  ifndef FILE_ATTRIBUTE_DEVICE
+#    define FILE_ATTRIBUTE_DEVICE 64
+#  endif
+  int attributes;
+  wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
 
-      if (wfilename == NULL)
-       return FALSE;
+  if (wfilename == NULL)
+    return FALSE;
 
-      if ((test & G_FILE_TEST_EXISTS) && (_waccess (wfilename, F_OK) == 0))
-       {
-         g_free (wfilename);
-         return TRUE;
-       }
-      
-      if (test & (G_FILE_TEST_IS_REGULAR |
-                 G_FILE_TEST_IS_DIR |
-                 G_FILE_TEST_IS_EXECUTABLE))
-       {
-         struct _stat s;
-         
-         if (_wstat (wfilename, &s) == 0)
-           {
-             if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
-               {
-                 g_free (wfilename);
-                 return TRUE;
-               }
-             
-             if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
-               {
-                 g_free (wfilename);
-                 return TRUE;
-               }
-             
-             if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
-                 (s.st_mode & _S_IEXEC))
-               {
-                 g_free (wfilename);
-                 return TRUE;
-               }
-           }
-       }
+  attributes = GetFileAttributesW (wfilename);
+
+  g_free (wfilename);
+
+  if (attributes == INVALID_FILE_ATTRIBUTES)
+    return FALSE;
 
-      g_free (wfilename);
+  if (test & G_FILE_TEST_EXISTS)
+    return TRUE;
       
-      return FALSE;
+  if (test & G_FILE_TEST_IS_REGULAR)
+    {
+      if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0)
+       return TRUE;
     }
-  else
+
+  if (test & G_FILE_TEST_IS_DIR)
+    {
+      if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
+       return TRUE;
+    }
+
+  /* "while" so that we can exit this "loop" with a simple "break" */
+  while (test & G_FILE_TEST_IS_EXECUTABLE)
     {
-      gchar *cp_filename = g_locale_from_utf8 (filename, -1, NULL, NULL, NULL);
+      const gchar *lastdot = strrchr (filename, '.');
+      const gchar *pathext = NULL, *p;
+      int extlen;
 
-      if (cp_filename == NULL)
-       return FALSE;
-      
-      if ((test & G_FILE_TEST_EXISTS) && (access (cp_filename, F_OK) == 0))
-       {
-         g_free (cp_filename);
-         return TRUE;
-       }
-      
-      if (test & (G_FILE_TEST_IS_REGULAR |
-                 G_FILE_TEST_IS_DIR |
-                 G_FILE_TEST_IS_EXECUTABLE))
+      if (lastdot == NULL)
+        break;
+
+      if (_stricmp (lastdot, ".exe") == 0 ||
+         _stricmp (lastdot, ".cmd") == 0 ||
+         _stricmp (lastdot, ".bat") == 0 ||
+         _stricmp (lastdot, ".com") == 0)
+       return TRUE;
+
+      /* Check if it is one of the types listed in %PATHEXT% */
+
+      pathext = g_getenv ("PATHEXT");
+      if (pathext == NULL)
+        break;
+
+      pathext = g_utf8_casefold (pathext, -1);
+
+      lastdot = g_utf8_casefold (lastdot, -1);
+      extlen = strlen (lastdot);
+
+      p = pathext;
+      while (TRUE)
        {
-         struct stat s;
-         
-         if (stat (cp_filename, &s) == 0)
+         const gchar *q = strchr (p, ';');
+         if (q == NULL)
+           q = p + strlen (p);
+         if (extlen == q - p &&
+             memcmp (lastdot, p, extlen) == 0)
            {
-             if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
-               {
-                 g_free (cp_filename);
-                 return TRUE;
-               }
-             
-             if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
-               {
-                 g_free (cp_filename);
-                 return TRUE;
-               }
-             
-             if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
-                 (s.st_mode & _S_IEXEC))
-               {
-                 g_free (cp_filename);
-                 return TRUE;
-               }
+             g_free ((gchar *) pathext);
+             g_free ((gchar *) lastdot);
+             return TRUE;
            }
+         if (*q)
+           p = q + 1;
+         else
+           break;
        }
 
-      g_free (cp_filename);
-      
-      return FALSE;
+      g_free ((gchar *) pathext);
+      g_free ((gchar *) lastdot);
+      break;
     }
+
+  return FALSE;
 #else
   if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
     return TRUE;
@@ -259,39 +324,10 @@ g_file_test (const gchar *filename,
 #endif
 }
 
-#ifdef G_OS_WIN32
-
-#undef g_file_test
-
-/* Binary compatibility version. Not for newly compiled code. */
-
-gboolean
-g_file_test (const gchar *filename,
-             GFileTest    test)
-{
-  gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
-  gboolean retval;
-
-  if (utf8_filename == NULL)
-    return FALSE;
-
-  retval = g_file_test_utf8 (utf8_filename, test);
-
-  g_free (utf8_filename);
-
-  return retval;
-}
-
-#endif
-
 GQuark
 g_file_error_quark (void)
 {
-  static GQuark q = 0;
-  if (q == 0)
-    q = g_quark_from_static_string ("g-file-error-quark");
-
-  return q;
+  return g_quark_from_static_string ("g-file-error-quark");
 }
 
 /**
@@ -465,97 +501,119 @@ g_file_error_from_errno (gint err_no)
 }
 
 static gboolean
-get_contents_stdio (const gchar *display_filename,
-                    FILE        *f,
-                    gchar      **contents,
-                    gsize       *length, 
-                    GError     **error)
+get_contents_stdio (const gchar  *display_filename,
+                    FILE         *f,
+                    gchar       **contents,
+                    gsize        *length,
+                    GError      **error)
 {
-  gchar buf[2048];
-  size_t bytes;
-  char *str;
-  size_t total_bytes;
-  size_t total_allocated;
-  
+  gchar buf[4096];
+  gsize bytes;
+  gchar *str = NULL;
+  gsize total_bytes = 0;
+  gsize total_allocated = 0;
+  gchar *tmp;
+
   g_assert (f != NULL);
 
-#define STARTING_ALLOC 64
-  
-  total_bytes = 0;
-  total_allocated = STARTING_ALLOC;
-  str = g_malloc (STARTING_ALLOC);
-  
   while (!feof (f))
     {
-      bytes = fread (buf, 1, 2048, f);
+      gint save_errno;
+
+      bytes = fread (buf, 1, sizeof (buf), f);
+      save_errno = errno;
 
       while ((total_bytes + bytes + 1) > total_allocated)
         {
-          total_allocated *= 2;
-          str = g_try_realloc (str, total_allocated);
+          if (str)
+            total_allocated *= 2;
+          else
+            total_allocated = MIN (bytes + 1, sizeof (buf));
 
-          if (str == NULL)
+          tmp = g_try_realloc (str, total_allocated);
+
+          if (tmp == NULL)
             {
               g_set_error (error,
                            G_FILE_ERROR,
                            G_FILE_ERROR_NOMEM,
                            _("Could not allocate %lu bytes to read file \"%s\""),
-                           (gulong) total_allocated, 
+                           (gulong) total_allocated,
                           display_filename);
 
               goto error;
             }
+
+         str = tmp;
         }
-      
+
       if (ferror (f))
         {
           g_set_error (error,
                        G_FILE_ERROR,
-                       g_file_error_from_errno (errno),
+                       g_file_error_from_errno (save_errno),
                        _("Error reading file '%s': %s"),
                        display_filename,
-                      g_strerror (errno));
+                      g_strerror (save_errno));
 
           goto error;
         }
 
       memcpy (str + total_bytes, buf, bytes);
+
+      if (total_bytes + bytes < total_bytes) 
+        {
+          g_set_error (error,
+                       G_FILE_ERROR,
+                       G_FILE_ERROR_FAILED,
+                       _("File \"%s\" is too large"),
+                       display_filename);
+
+          goto error;
+        }
+
       total_bytes += bytes;
     }
 
   fclose (f);
 
+  if (total_allocated == 0)
+    {
+      str = g_new (gchar, 1);
+      total_bytes = 0;
+    }
+
   str[total_bytes] = '\0';
-  
+
   if (length)
     *length = total_bytes;
-  
+
   *contents = str;
-  
+
   return TRUE;
 
  error:
 
   g_free (str);
   fclose (f);
-  
-  return FALSE;  
+
+  return FALSE;
 }
 
 #ifndef G_OS_WIN32
 
 static gboolean
-get_contents_regfile (const gchar *display_filename,
-                      struct stat *stat_buf,
-                      gint         fd,
-                      gchar      **contents,
-                      gsize       *length,
-                      GError     **error)
+get_contents_regfile (const gchar  *display_filename,
+                      struct stat  *stat_buf,
+                      gint          fd,
+                      gchar       **contents,
+                      gsize        *length,
+                      GError      **error)
 {
   gchar *buf;
-  size_t bytes_read;
-  size_t size;
-  size_t alloc_size;
+  gsize bytes_read;
+  gsize size;
+  gsize alloc_size;
   
   size = stat_buf->st_size;
 
@@ -585,13 +643,15 @@ get_contents_regfile (const gchar *display_filename,
         {
           if (errno != EINTR) 
             {
+             int save_errno = errno;
+
               g_free (buf);
               g_set_error (error,
                            G_FILE_ERROR,
-                           g_file_error_from_errno (errno),
+                           g_file_error_from_errno (save_errno),
                            _("Failed to read from file '%s': %s"),
                            display_filename, 
-                          g_strerror (errno));
+                          g_strerror (save_errno));
 
              goto error;
             }
@@ -621,10 +681,10 @@ get_contents_regfile (const gchar *display_filename,
 }
 
 static gboolean
-get_contents_posix (const gchar *filename,
-                    gchar      **contents,
-                    gsize       *length,
-                    GError     **error)
+get_contents_posix (const gchar  *filename,
+                    gchar       **contents,
+                    gsize        *length,
+                    GError      **error)
 {
   struct stat stat_buf;
   gint fd;
@@ -635,12 +695,14 @@ get_contents_posix (const gchar *filename,
 
   if (fd < 0)
     {
+      int save_errno = errno;
+
       g_set_error (error,
                    G_FILE_ERROR,
-                   g_file_error_from_errno (errno),
+                   g_file_error_from_errno (save_errno),
                    _("Failed to open file '%s': %s"),
                    display_filename, 
-                  g_strerror (errno));
+                  g_strerror (save_errno));
       g_free (display_filename);
 
       return FALSE;
@@ -649,13 +711,15 @@ get_contents_posix (const gchar *filename,
   /* I don't think this will ever fail, aside from ENOMEM, but. */
   if (fstat (fd, &stat_buf) < 0)
     {
+      int save_errno = errno;
+
       close (fd);
       g_set_error (error,
                    G_FILE_ERROR,
-                   g_file_error_from_errno (errno),
+                   g_file_error_from_errno (save_errno),
                    _("Failed to get attributes of file '%s': fstat() failed: %s"),
                    display_filename, 
-                  g_strerror (errno));
+                  g_strerror (save_errno));
       g_free (display_filename);
 
       return FALSE;
@@ -682,12 +746,14 @@ get_contents_posix (const gchar *filename,
       
       if (f == NULL)
         {
+         int save_errno = errno;
+
           g_set_error (error,
                        G_FILE_ERROR,
-                       g_file_error_from_errno (errno),
+                       g_file_error_from_errno (save_errno),
                        _("Failed to open file '%s': fdopen() failed: %s"),
                        display_filename, 
-                      g_strerror (errno));
+                      g_strerror (save_errno));
           g_free (display_filename);
 
           return FALSE;
@@ -703,27 +769,27 @@ get_contents_posix (const gchar *filename,
 #else  /* G_OS_WIN32 */
 
 static gboolean
-get_contents_win32 (const gchar *filename,
-                   gchar      **contents,
-                   gsize       *length,
-                   GError     **error)
+get_contents_win32 (const gchar  *filename,
+                   gchar       **contents,
+                   gsize        *length,
+                   GError      **error)
 {
   FILE *f;
   gboolean retval;
-  wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
   gchar *display_filename = g_filename_display_name (filename);
+  int save_errno;
   
-  f = _wfopen (wfilename, L"rb");
-  g_free (wfilename);
+  f = g_fopen (filename, "rb");
+  save_errno = errno;
 
   if (f == NULL)
     {
       g_set_error (error,
                    G_FILE_ERROR,
-                   g_file_error_from_errno (errno),
+                   g_file_error_from_errno (save_errno),
                    _("Failed to open file '%s': %s"),
                    display_filename,
-                  g_strerror (errno));
+                  g_strerror (save_errno));
       g_free (display_filename);
 
       return FALSE;
@@ -740,25 +806,29 @@ get_contents_win32 (const gchar *filename,
 /**
  * g_file_get_contents:
  * @filename: name of a file to read contents from, in the GLib file name encoding
- * @contents: location to store an allocated string
- * @length: location to store length in bytes of the contents
- * @error: return location for a #GError
- * 
+ * @contents: location to store an allocated string, use g_free() to free
+ *     the returned string
+ * @length: location to store length in bytes of the contents, or %NULL
+ * @error: return location for a #GError, or %NULL
+ *
  * Reads an entire file into allocated memory, with good error
- * checking. If @error is set, %FALSE is returned, and @contents is set
- * to %NULL. If %TRUE is returned, @error will not be set, and @contents
- * will be set to the file contents.  The string stored in @contents
- * will be nul-terminated, so for text files you can pass %NULL for the
- * @length argument.  The error domain is #G_FILE_ERROR. Possible
- * error codes are those in the #GFileError enumeration.
+ * checking.
+ *
+ * If the call was successful, it returns %TRUE and sets @contents to the file
+ * contents and @length to the length of the file contents in bytes. The string
+ * stored in @contents will be nul-terminated, so for text files you can pass
+ * %NULL for the @length argument. If the call was not successful, it returns
+ * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
+ * codes are those in the #GFileError enumeration. In the error case,
+ * @contents is set to %NULL and @length is set to zero.
  *
- * Return value: %TRUE on success, %FALSE if error is set
+ * Return value: %TRUE on success, %FALSE if an error occurred
  **/
 gboolean
-g_file_get_contents (const gchar *filename,
-                     gchar      **contents,
-                     gsize       *length,
-                     GError     **error)
+g_file_get_contents (const gchar  *filename,
+                     gchar       **contents,
+                     gsize        *length,
+                     GError      **error)
 {  
   g_return_val_if_fail (filename != NULL, FALSE);
   g_return_val_if_fail (contents != NULL, FALSE);
@@ -774,128 +844,366 @@ g_file_get_contents (const gchar *filename,
 #endif
 }
 
-#ifdef G_OS_WIN32
-
-#undef g_file_get_contents
-
-/* Binary compatibility version. Not for newly compiled code. */
-
-gboolean
-g_file_get_contents (const gchar *filename,
-                     gchar      **contents,
-                     gsize       *length,
-                     GError     **error)
+static gboolean
+rename_file (const char  *old_name,
+            const char  *new_name,
+            GError     **err)
 {
-  gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
-  gboolean retval;
-
-  if (utf8_filename == NULL)
-    return FALSE;
-
-  retval = g_file_get_contents (utf8_filename, contents, length, error);
-
-  g_free (utf8_filename);
+  errno = 0;
+  if (g_rename (old_name, new_name) == -1)
+    {
+      int save_errno = errno;
+      gchar *display_old_name = g_filename_display_name (old_name);
+      gchar *display_new_name = g_filename_display_name (new_name);
 
-  return retval;
+      g_set_error (err,
+                  G_FILE_ERROR,
+                  g_file_error_from_errno (save_errno),
+                  _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
+                  display_old_name,
+                  display_new_name,
+                  g_strerror (save_errno));
+
+      g_free (display_old_name);
+      g_free (display_new_name);
+      
+      return FALSE;
+    }
+  
+  return TRUE;
 }
 
-#endif
-
-/*
- * mkstemp() implementation is from the GNU C library.
- * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
- */
-/**
- * g_mkstemp:
- * @tmpl: template filename
- *
- * Opens a temporary file. See the mkstemp() documentation
- * on most UNIX-like systems. This is a portability wrapper, which simply calls 
- * mkstemp() on systems that have it, and implements 
- * it in GLib otherwise.
- *
- * The parameter is a string that should match the rules for
- * mkstemp(), i.e. end in "XXXXXX". The X string will 
- * be modified to form the name of a file that didn't exist.
- * The string should be in the GLib file name encoding. Most importantly, 
- * on Windows it should be in UTF-8.
- *
- * Return value: A file handle (as from open()) to the file
- * opened for reading and writing. The file is opened in binary mode
- * on platforms where there is a difference. The file handle should be
- * closed with close(). In case of errors, -1 is returned.
- */
-gint
-g_mkstemp (gchar *tmpl)
+static gchar *
+write_to_temp_file (const gchar  *contents,
+                   gssize        length,
+                   const gchar  *dest_file,
+                   GError      **err)
 {
-#ifdef HAVE_MKSTEMP
-  return mkstemp (tmpl);
-#else
-  int len;
-  char *XXXXXX;
-  int count, fd;
-  static const char letters[] =
-    "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
-  static const int NLETTERS = sizeof (letters) - 1;
-  glong value;
-  GTimeVal tv;
-  static int counter = 0;
-
-  len = strlen (tmpl);
-  if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
-    return -1;
+  gchar *tmp_name;
+  gchar *display_name;
+  gchar *retval;
+  FILE *file;
+  gint fd;
+  int save_errno;
 
-  /* This is where the Xs start.  */
-  XXXXXX = &tmpl[len - 6];
+  retval = NULL;
+  
+  tmp_name = g_strdup_printf ("%s.XXXXXX", dest_file);
 
-  /* Get some more or less random data.  */
-  g_get_current_time (&tv);
-  value = (tv.tv_usec ^ tv.tv_sec) + counter++;
+  errno = 0;
+  fd = g_mkstemp_full (tmp_name, O_RDWR | O_BINARY, 0666);
+  save_errno = errno;
 
-  for (count = 0; count < 100; value += 7777, ++count)
+  display_name = g_filename_display_name (tmp_name);
+      
+  if (fd == -1)
     {
-      glong v = value;
-
-      /* Fill in the random bits.  */
-      XXXXXX[0] = letters[v % NLETTERS];
-      v /= NLETTERS;
-      XXXXXX[1] = letters[v % NLETTERS];
-      v /= NLETTERS;
-      XXXXXX[2] = letters[v % NLETTERS];
-      v /= NLETTERS;
-      XXXXXX[3] = letters[v % NLETTERS];
-      v /= NLETTERS;
-      XXXXXX[4] = letters[v % NLETTERS];
-      v /= NLETTERS;
-      XXXXXX[5] = letters[v % NLETTERS];
+      g_set_error (err,
+                  G_FILE_ERROR,
+                  g_file_error_from_errno (save_errno),
+                  _("Failed to create file '%s': %s"),
+                  display_name, g_strerror (save_errno));
+      
+      goto out;
+    }
 
-      /* tmpl is in UTF-8 on Windows, thus use g_open() */
-      fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
+  errno = 0;
+  file = fdopen (fd, "wb");
+  if (!file)
+    {
+      save_errno = errno;
+      g_set_error (err,
+                  G_FILE_ERROR,
+                  g_file_error_from_errno (save_errno),
+                  _("Failed to open file '%s' for writing: fdopen() failed: %s"),
+                  display_name,
+                  g_strerror (save_errno));
 
-      if (fd >= 0)
-       return fd;
-      else if (errno != EEXIST)
-       /* Any other error will apply also to other names we might
-        *  try, and there are 2^32 or so of them, so give up now.
-        */
-       return -1;
+      close (fd);
+      g_unlink (tmp_name);
+      
+      goto out;
     }
 
-  /* We got out of the loop because we ran out of combinations to try.  */
-  return -1;
-#endif
-}
+  if (length > 0)
+    {
+      gsize n_written;
+      
+      errno = 0;
 
-#ifdef G_OS_WIN32
+      n_written = fwrite (contents, 1, length, file);
 
-#undef g_mkstemp
+      if (n_written < length)
+       {
+         save_errno = errno;
+      
+         g_set_error (err,
+                      G_FILE_ERROR,
+                      g_file_error_from_errno (save_errno),
+                      _("Failed to write file '%s': fwrite() failed: %s"),
+                      display_name,
+                      g_strerror (save_errno));
+
+         fclose (file);
+         g_unlink (tmp_name);
+         
+         goto out;
+       }
+    }
 
-/* Binary compatibility version. Not for newly compiled code. */
+  errno = 0;
+  if (fflush (file) != 0)
+    { 
+      save_errno = errno;
+      
+      g_set_error (err,
+                  G_FILE_ERROR,
+                  g_file_error_from_errno (save_errno),
+                  _("Failed to write file '%s': fflush() failed: %s"),
+                  display_name, 
+                  g_strerror (save_errno));
+
+      g_unlink (tmp_name);
+      
+      goto out;
+    }
+
+#ifdef BTRFS_SUPER_MAGIC
+  {
+    struct statfs buf;
+
+    /* On Linux, on btrfs, skip the fsync since rename-over-existing is
+     * guaranteed to be atomic and this is the only case in which we
+     * would fsync() anyway.
+     */
 
+    if (fstatfs (fd, &buf) == 0 && buf.f_type == BTRFS_SUPER_MAGIC)
+      goto no_fsync;
+  }
+#endif
+  
+#ifdef HAVE_FSYNC
+  {
+    struct stat statbuf;
+
+    errno = 0;
+    /* If the final destination exists and is > 0 bytes, we want to sync the
+     * newly written file to ensure the data is on disk when we rename over
+     * the destination. Otherwise if we get a system crash we can lose both
+     * the new and the old file on some filesystems. (I.E. those that don't
+     * guarantee the data is written to the disk before the metadata.)
+     */
+    if (g_lstat (dest_file, &statbuf) == 0 &&
+       statbuf.st_size > 0 &&
+       fsync (fileno (file)) != 0)
+      {
+       save_errno = errno;
+
+       g_set_error (err,
+                    G_FILE_ERROR,
+                    g_file_error_from_errno (save_errno),
+                    _("Failed to write file '%s': fsync() failed: %s"),
+                    display_name,
+                    g_strerror (save_errno));
+
+       g_unlink (tmp_name);
+
+       goto out;
+      }
+  }
+#endif
+ no_fsync:
+  
+  errno = 0;
+  if (fclose (file) == EOF)
+    { 
+      save_errno = errno;
+      
+      g_set_error (err,
+                  G_FILE_ERROR,
+                  g_file_error_from_errno (save_errno),
+                  _("Failed to close file '%s': fclose() failed: %s"),
+                  display_name, 
+                  g_strerror (save_errno));
+
+      g_unlink (tmp_name);
+      
+      goto out;
+    }
+
+  retval = g_strdup (tmp_name);
+  
+ out:
+  g_free (tmp_name);
+  g_free (display_name);
+  
+  return retval;
+}
+
+/**
+ * g_file_set_contents:
+ * @filename: name of a file to write @contents to, in the GLib file name
+ *   encoding
+ * @contents: string to write to the file
+ * @length: length of @contents, or -1 if @contents is a nul-terminated string
+ * @error: return location for a #GError, or %NULL
+ *
+ * Writes all of @contents to a file named @filename, with good error checking.
+ * If a file called @filename already exists it will be overwritten.
+ *
+ * This write is atomic in the sense that it is first written to a temporary
+ * file which is then renamed to the final name. Notes:
+ * <itemizedlist>
+ * <listitem>
+ *    On Unix, if @filename already exists hard links to @filename will break.
+ *    Also since the file is recreated, existing permissions, access control
+ *    lists, metadata etc. may be lost. If @filename is a symbolic link,
+ *    the link itself will be replaced, not the linked file.
+ * </listitem>
+ * <listitem>
+ *   On Windows renaming a file will not remove an existing file with the
+ *   new name, so on Windows there is a race condition between the existing
+ *   file being removed and the temporary file being renamed.
+ * </listitem>
+ * <listitem>
+ *   On Windows there is no way to remove a file that is open to some
+ *   process, or mapped into memory. Thus, this function will fail if
+ *   @filename already exists and is open.
+ * </listitem>
+ * </itemizedlist>
+ *
+ * If the call was sucessful, it returns %TRUE. If the call was not successful,
+ * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
+ * Possible error codes are those in the #GFileError enumeration.
+ *
+ * Note that the name for the temporary file is constructed by appending up
+ * to 7 characters to @filename.
+ *
+ * Return value: %TRUE on success, %FALSE if an error occurred
+ *
+ * Since: 2.8
+ **/
+gboolean
+g_file_set_contents (const gchar  *filename,
+                    const gchar  *contents,
+                    gssize        length,
+                    GError      **error)
+{
+  gchar *tmp_filename;
+  gboolean retval;
+  GError *rename_error = NULL;
+  
+  g_return_val_if_fail (filename != NULL, FALSE);
+  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
+  g_return_val_if_fail (contents != NULL || length == 0, FALSE);
+  g_return_val_if_fail (length >= -1, FALSE);
+  
+  if (length == -1)
+    length = strlen (contents);
+
+  tmp_filename = write_to_temp_file (contents, length, filename, error);
+  
+  if (!tmp_filename)
+    {
+      retval = FALSE;
+      goto out;
+    }
+
+  if (!rename_file (tmp_filename, filename, &rename_error))
+    {
+#ifndef G_OS_WIN32
+
+      g_unlink (tmp_filename);
+      g_propagate_error (error, rename_error);
+      retval = FALSE;
+      goto out;
+
+#else /* G_OS_WIN32 */
+      
+      /* Renaming failed, but on Windows this may just mean
+       * the file already exists. So if the target file
+       * exists, try deleting it and do the rename again.
+       */
+      if (!g_file_test (filename, G_FILE_TEST_EXISTS))
+       {
+         g_unlink (tmp_filename);
+         g_propagate_error (error, rename_error);
+         retval = FALSE;
+         goto out;
+       }
+
+      g_error_free (rename_error);
+      
+      if (g_unlink (filename) == -1)
+       {
+          gchar *display_filename = g_filename_display_name (filename);
+
+         int save_errno = errno;
+         
+         g_set_error (error,
+                      G_FILE_ERROR,
+                      g_file_error_from_errno (save_errno),
+                      _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
+                      display_filename,
+                      g_strerror (save_errno));
+
+         g_free (display_filename);
+         g_unlink (tmp_filename);
+         retval = FALSE;
+         goto out;
+       }
+      
+      if (!rename_file (tmp_filename, filename, error))
+       {
+         g_unlink (tmp_filename);
+         retval = FALSE;
+         goto out;
+       }
+
+#endif
+    }
+
+  retval = TRUE;
+  
+ out:
+  g_free (tmp_filename);
+  return retval;
+}
+
+/**
+ * g_mkstemp_full:
+ * @tmpl: template filename
+ * @flags: flags to pass to an open() call in addition to O_EXCL and
+ *         O_CREAT, which are passed automatically
+ * @mode: permissios to create the temporary file with
+ *
+ * Opens a temporary file. See the mkstemp() documentation
+ * on most UNIX-like systems.
+ *
+ * The parameter is a string that should follow the rules for
+ * mkstemp() templates, i.e. contain the string "XXXXXX".
+ * g_mkstemp_full() is slightly more flexible than mkstemp()
+ * in that the sequence does not have to occur at the very end of the
+ * template and you can pass a @mode and additional @flags. The X
+ * string will be modified to form the name of a file that didn't exist.
+ * The string should be in the GLib file name encoding. Most importantly,
+ * on Windows it should be in UTF-8.
+ *
+ * Return value: A file handle (as from open()) to the file
+ *     opened for reading and writing. The file handle should be
+ *     closed with close(). In case of errors, -1 is returned.
+ *
+ * Since: 2.22
+ */
+/*
+ * g_mkstemp_full based on the mkstemp implementation from the GNU C library.
+ * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
+ */
 gint
-g_mkstemp (gchar *tmpl)
+g_mkstemp_full (gchar *tmpl, 
+                int    flags,
+               int    mode)
 {
-  int len;
   char *XXXXXX;
   int count, fd;
   static const char letters[] =
@@ -905,12 +1213,17 @@ g_mkstemp (gchar *tmpl)
   GTimeVal tv;
   static int counter = 0;
 
-  len = strlen (tmpl);
-  if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
-    return -1;
+  g_return_val_if_fail (tmpl != NULL, -1);
+
 
-  /* This is where the Xs start.  */
-  XXXXXX = &tmpl[len - 6];
+  /* find the last occurrence of "XXXXXX" */
+  XXXXXX = g_strrstr (tmpl, "XXXXXX");
+
+  if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
+    {
+      errno = EINVAL;
+      return -1;
+    }
 
   /* Get some more or less random data.  */
   g_get_current_time (&tv);
@@ -933,10 +1246,8 @@ g_mkstemp (gchar *tmpl)
       v /= NLETTERS;
       XXXXXX[5] = letters[v % NLETTERS];
 
-      /* This is the backward compatibility system codepage version,
-       * thus use normal open().
-       */
-      fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
+      /* tmpl is in UTF-8 on Windows, thus use g_open() */
+      fd = g_open (tmpl, flags | O_CREAT | O_EXCL, mode);
 
       if (fd >= 0)
        return fd;
@@ -948,22 +1259,49 @@ g_mkstemp (gchar *tmpl)
     }
 
   /* We got out of the loop because we ran out of combinations to try.  */
+  errno = EEXIST;
   return -1;
 }
 
-#endif
+/**
+ * g_mkstemp:
+ * @tmpl: template filename
+ *
+ * Opens a temporary file. See the mkstemp() documentation
+ * on most UNIX-like systems. 
+ *
+ * The parameter is a string that should follow the rules for
+ * mkstemp() templates, i.e. contain the string "XXXXXX". 
+ * g_mkstemp() is slightly more flexible than mkstemp()
+ * in that the sequence does not have to occur at the very end of the 
+ * template. The X string will 
+ * be modified to form the name of a file that didn't exist.
+ * The string should be in the GLib file name encoding. Most importantly, 
+ * on Windows it should be in UTF-8.
+ *
+ * Return value: A file handle (as from open()) to the file
+ * opened for reading and writing. The file is opened in binary mode
+ * on platforms where there is a difference. The file handle should be
+ * closed with close(). In case of errors, -1 is returned.  
+ */ 
+gint
+g_mkstemp (gchar *tmpl)
+{
+  return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
+}
 
 /**
  * g_file_open_tmp:
- * @tmpl: Template for file name, as in g_mkstemp(), basename only
- * @name_used: location to store actual name used
+ * @tmpl: Template for file name, as in g_mkstemp(), basename only,
+ *        or %NULL, to a default template
+ * @name_used: location to store actual name used, or %NULL
  * @error: return location for a #GError
  *
  * Opens a file for writing in the preferred directory for temporary
  * files (as returned by g_get_tmp_dir()). 
  *
- * @tmpl should be a string in the GLib file name encoding ending with
- * six 'X' characters, as the parameter to g_mkstemp() (or mkstemp()).
+ * @tmpl should be a string in the GLib file name encoding containing 
+ * a sequence of six 'X' characters, as the parameter to g_mkstemp().
  * However, unlike these functions, the template should only be a
  * basename, no directory components are allowed. If template is
  * %NULL, a default template is used.
@@ -982,13 +1320,13 @@ g_mkstemp (gchar *tmpl)
  * and @error will be set.
  **/
 gint
-g_file_open_tmp (const gchar *tmpl,
-                gchar      **name_used,
-                GError     **error)
+g_file_open_tmp (const gchar  *tmpl,
+                gchar       **name_used,
+                GError      **error)
 {
   int retval;
   const char *tmpdir;
-  char *sep;
+  const char *sep;
   char *fulltemplate;
   const char *slash;
 
@@ -1016,14 +1354,13 @@ g_file_open_tmp (const gchar *tmpl,
       return -1;
     }
   
-  if (strlen (tmpl) < 6 ||
-      strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
+  if (strstr (tmpl, "XXXXXX") == NULL)
     {
       gchar *display_tmpl = g_filename_display_name (tmpl);
       g_set_error (error,
                   G_FILE_ERROR,
                   G_FILE_ERROR_FAILED,
-                  _("Template '%s' doesn't end with XXXXXX"),
+                  _("Template '%s' doesn't contain XXXXXX"),
                   display_tmpl);
       g_free (display_tmpl);
       return -1;
@@ -1042,12 +1379,14 @@ g_file_open_tmp (const gchar *tmpl,
 
   if (retval == -1)
     {
+      int save_errno = errno;
       gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
+
       g_set_error (error,
                   G_FILE_ERROR,
-                  g_file_error_from_errno (errno),
+                  g_file_error_from_errno (save_errno),
                   _("Failed to create file '%s': %s"),
-                  display_fulltemplate, g_strerror (errno));
+                  display_fulltemplate, g_strerror (save_errno));
       g_free (display_fulltemplate);
       g_free (fulltemplate);
       return -1;
@@ -1061,43 +1400,11 @@ g_file_open_tmp (const gchar *tmpl,
   return retval;
 }
 
-#ifdef G_OS_WIN32
-
-#undef g_file_open_tmp
-
-/* Binary compatibility version. Not for newly compiled code. */
-
-gint
-g_file_open_tmp (const gchar *tmpl,
-                gchar      **name_used,
-                GError     **error)
-{
-  gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
-  gchar *utf8_name_used;
-  gint retval;
-
-  if (utf8_tmpl == NULL)
-    return -1;
-
-  retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
-  
-  if (retval == -1)
-    return -1;
-
-  if (name_used)
-    *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
-
-  g_free (utf8_name_used);
-
-  return retval;
-}
-
-#endif
-
 static gchar *
-g_build_pathv (const gchar *separator,
-              const gchar *first_element,
-              va_list      args)
+g_build_path_va (const gchar  *separator,
+                const gchar  *first_element,
+                va_list      *args,
+                gchar       **str_array)
 {
   GString *result;
   gint separator_len = strlen (separator);
@@ -1106,10 +1413,14 @@ g_build_pathv (const gchar *separator,
   const gchar *single_element = NULL;
   const gchar *next_element;
   const gchar *last_trailing = NULL;
+  gint i = 0;
 
   result = g_string_new (NULL);
 
-  next_element = first_element;
+  if (str_array)
+    next_element = str_array[i++];
+  else
+    next_element = first_element;
 
   while (TRUE)
     {
@@ -1120,7 +1431,10 @@ g_build_pathv (const gchar *separator,
       if (next_element)
        {
          element = next_element;
-         next_element = va_arg (args, gchar *);
+         if (str_array)
+           next_element = str_array[i++];
+         else
+           next_element = va_arg (*args, gchar *);
        }
       else
        break;
@@ -1133,8 +1447,7 @@ g_build_pathv (const gchar *separator,
 
       if (separator_len)
        {
-         while (start &&
-                strncmp (start, separator, separator_len) == 0)
+         while (strncmp (start, separator, separator_len) == 0)
            start += separator_len;
        }
 
@@ -1191,6 +1504,30 @@ g_build_pathv (const gchar *separator,
 }
 
 /**
+ * g_build_pathv:
+ * @separator: a string used to separator the elements of the path.
+ * @args: %NULL-terminated array of strings containing the path elements.
+ * 
+ * Behaves exactly like g_build_path(), but takes the path elements 
+ * as a string array, instead of varargs. This function is mainly
+ * meant for language bindings.
+ *
+ * Return value: a newly-allocated string that must be freed with g_free().
+ *
+ * Since: 2.8
+ */
+gchar *
+g_build_pathv (const gchar  *separator,
+              gchar       **args)
+{
+  if (!args)
+    return NULL;
+
+  return g_build_path_va (separator, NULL, NULL, args);
+}
+
+
+/**
  * g_build_path:
  * @separator: a string used to separator the elements of the path.
  * @first_element: the first element in the path
@@ -1237,54 +1574,22 @@ g_build_path (const gchar *separator,
   g_return_val_if_fail (separator != NULL, NULL);
 
   va_start (args, first_element);
-  str = g_build_pathv (separator, first_element, args);
+  str = g_build_path_va (separator, first_element, &args, NULL);
   va_end (args);
 
   return str;
 }
 
-/**
- * g_build_filename:
- * @first_element: the first element in the path
- * @Varargs: remaining elements in path, terminated by %NULL
- * 
- * Creates a filename from a series of elements using the correct
- * separator for filenames.
- *
- * On Unix, this function behaves identically to <literal>g_build_path
- * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
- *
- * On Windows, it takes into account that either the backslash
- * (<literal>\</literal> or slash (<literal>/</literal>) can be used
- * as separator in filenames, but otherwise behaves as on Unix. When
- * file pathname separators need to be inserted, the one that last
- * previously occurred in the parameters (reading from left to right)
- * is used.
- *
- * No attempt is made to force the resulting filename to be an absolute
- * path. If the first element is a relative path, the result will
- * be a relative path. 
- * 
- * Return value: a newly-allocated string that must be freed with g_free().
- **/
-gchar *
-g_build_filename (const gchar *first_element, 
-                 ...)
-{
-#ifndef G_OS_WIN32
-  gchar *str;
-  va_list args;
-
-  va_start (args, first_element);
-  str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
-  va_end (args);
+#ifdef G_OS_WIN32
 
-  return str;
-#else
-  /* Code copied from g_build_pathv(), and modifed to use two
+static gchar *
+g_build_pathname_va (const gchar  *first_element,
+                    va_list      *args,
+                    gchar       **str_array)
+{
+  /* Code copied from g_build_pathv(), and modified to use two
    * alternative single-character separators.
    */
-  va_list args;
   GString *result;
   gboolean is_first = TRUE;
   gboolean have_leading = FALSE;
@@ -1292,13 +1597,15 @@ g_build_filename (const gchar *first_element,
   const gchar *next_element;
   const gchar *last_trailing = NULL;
   gchar current_separator = '\\';
-
-  va_start (args, first_element);
+  gint i = 0;
 
   result = g_string_new (NULL);
 
-  next_element = first_element;
-
+  if (str_array)
+    next_element = str_array[i++];
+  else
+    next_element = first_element;
+  
   while (TRUE)
     {
       const gchar *element;
@@ -1308,7 +1615,10 @@ g_build_filename (const gchar *first_element,
       if (next_element)
        {
          element = next_element;
-         next_element = va_arg (args, gchar *);
+         if (str_array)
+           next_element = str_array[i++];
+         else
+           next_element = va_arg (*args, gchar *);
        }
       else
        break;
@@ -1370,8 +1680,6 @@ g_build_filename (const gchar *first_element,
       is_first = FALSE;
     }
 
-  va_end (args);
-
   if (single_element)
     {
       g_string_free (result, TRUE);
@@ -1384,10 +1692,147 @@ g_build_filename (const gchar *first_element,
   
       return g_string_free (result, FALSE);
     }
+}
+
 #endif
+
+/**
+ * g_build_filenamev:
+ * @args: %NULL-terminated array of strings containing the path elements.
+ * 
+ * Behaves exactly like g_build_filename(), but takes the path elements 
+ * as a string array, instead of varargs. This function is mainly
+ * meant for language bindings.
+ *
+ * Return value: a newly-allocated string that must be freed with g_free().
+ * 
+ * Since: 2.8
+ */
+gchar *
+g_build_filenamev (gchar **args)
+{
+  gchar *str;
+
+#ifndef G_OS_WIN32
+  str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
+#else
+  str = g_build_pathname_va (NULL, NULL, args);
+#endif
+
+  return str;
 }
 
 /**
+ * g_build_filename:
+ * @first_element: the first element in the path
+ * @Varargs: remaining elements in path, terminated by %NULL
+ * 
+ * Creates a filename from a series of elements using the correct
+ * separator for filenames.
+ *
+ * On Unix, this function behaves identically to <literal>g_build_path
+ * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
+ *
+ * On Windows, it takes into account that either the backslash
+ * (<literal>\</literal> or slash (<literal>/</literal>) can be used
+ * as separator in filenames, but otherwise behaves as on Unix. When
+ * file pathname separators need to be inserted, the one that last
+ * previously occurred in the parameters (reading from left to right)
+ * is used.
+ *
+ * No attempt is made to force the resulting filename to be an absolute
+ * path. If the first element is a relative path, the result will
+ * be a relative path. 
+ * 
+ * Return value: a newly-allocated string that must be freed with g_free().
+ **/
+gchar *
+g_build_filename (const gchar *first_element, 
+                 ...)
+{
+  gchar *str;
+  va_list args;
+
+  va_start (args, first_element);
+#ifndef G_OS_WIN32
+  str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
+#else
+  str = g_build_pathname_va (first_element, &args, NULL);
+#endif
+  va_end (args);
+
+  return str;
+}
+
+#define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
+#define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
+#define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
+#define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
+#define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
+#define EXABYTE_FACTOR  (PETABYTE_FACTOR * KILOBYTE_FACTOR)
+
+/**
+ * g_format_size_for_display:
+ * @size: a size in bytes.
+ * 
+ * Formats a size (for example the size of a file) into a human readable string.
+ * Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed 
+ * rounded to the nearest  tenth. E.g. the file size 3292528 bytes will be
+ * converted into the string "3.1 MB".
+ *
+ * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
+ *
+ * This string should be freed with g_free() when not needed any longer.
+ *
+ * Returns: a newly-allocated formatted string containing a human readable
+ *          file size.
+ *
+ * Since: 2.16
+ **/
+char *
+g_format_size_for_display (goffset size)
+{
+  if (size < (goffset) KILOBYTE_FACTOR)
+    return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
+  else
+    {
+      gdouble displayed_size;
+      
+      if (size < (goffset) MEGABYTE_FACTOR)
+       {
+         displayed_size = (gdouble) size / (gdouble) KILOBYTE_FACTOR;
+         return g_strdup_printf (_("%.1f KB"), displayed_size);
+       }
+      else if (size < (goffset) GIGABYTE_FACTOR)
+       {
+         displayed_size = (gdouble) size / (gdouble) MEGABYTE_FACTOR;
+         return g_strdup_printf (_("%.1f MB"), displayed_size);
+       }
+      else if (size < (goffset) TERABYTE_FACTOR)
+       {
+         displayed_size = (gdouble) size / (gdouble) GIGABYTE_FACTOR;
+         return g_strdup_printf (_("%.1f GB"), displayed_size);
+       }
+      else if (size < (goffset) PETABYTE_FACTOR)
+       {
+         displayed_size = (gdouble) size / (gdouble) TERABYTE_FACTOR;
+         return g_strdup_printf (_("%.1f TB"), displayed_size);
+       }
+      else if (size < (goffset) EXABYTE_FACTOR)
+       {
+         displayed_size = (gdouble) size / (gdouble) PETABYTE_FACTOR;
+         return g_strdup_printf (_("%.1f PB"), displayed_size);
+       }
+      else
+        {
+         displayed_size = (gdouble) size / (gdouble) EXABYTE_FACTOR;
+         return g_strdup_printf (_("%.1f EB"), displayed_size);
+        }
+    }
+}
+
+
+/**
  * g_file_read_link:
  * @filename: the symbolic link
  * @error: return location for a #GError
@@ -1396,14 +1841,14 @@ g_build_filename (const gchar *first_element,
  * readlink() function.  The returned string is in the encoding used
  * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
  *
- * Returns: A newly allocated string with the contents of the symbolic link, 
+ * Returns: A newly-allocated string with the contents of the symbolic link, 
  *          or %NULL if an error occurred.
  *
  * Since: 2.4
  */
 gchar *
-g_file_read_link (const gchar *filename,
-                 GError     **error)
+g_file_read_link (const gchar  *filename,
+                 GError      **error)
 {
 #ifdef HAVE_READLINK
   gchar *buffer;
@@ -1417,14 +1862,16 @@ g_file_read_link (const gchar *filename,
     {
       read_size = readlink (filename, buffer, size);
       if (read_size < 0) {
+       int save_errno = errno;
        gchar *display_filename = g_filename_display_name (filename);
+
        g_free (buffer);
        g_set_error (error,
                     G_FILE_ERROR,
-                    g_file_error_from_errno (errno),
+                    g_file_error_from_errno (save_errno),
                     _("Failed to read the symbolic link '%s': %s"),
                     display_filename, 
-                    g_strerror (errno));
+                    g_strerror (save_errno));
        g_free (display_filename);
        
        return NULL;
@@ -1440,11 +1887,153 @@ g_file_read_link (const gchar *filename,
       buffer = g_realloc (buffer, size);
     }
 #else
-  g_set_error (error,
-              G_FILE_ERROR,
-              G_FILE_ERROR_INVAL,
-              _("Symbolic links not supported"));
+  g_set_error_literal (error,
+                       G_FILE_ERROR,
+                       G_FILE_ERROR_INVAL,
+                       _("Symbolic links not supported"));
        
   return NULL;
 #endif
 }
+
+/* NOTE : Keep this part last to ensure nothing in this file uses the
+ * below binary compatibility versions.
+ */
+#if defined (G_OS_WIN32) && !defined (_WIN64)
+
+/* Binary compatibility versions. Will be called by code compiled
+ * against quite old (pre-2.8, I think) headers only, not from more
+ * recently compiled code.
+ */
+
+#undef g_file_test
+
+gboolean
+g_file_test (const gchar *filename,
+             GFileTest    test)
+{
+  gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
+  gboolean retval;
+
+  if (utf8_filename == NULL)
+    return FALSE;
+
+  retval = g_file_test_utf8 (utf8_filename, test);
+
+  g_free (utf8_filename);
+
+  return retval;
+}
+
+#undef g_file_get_contents
+
+gboolean
+g_file_get_contents (const gchar  *filename,
+                     gchar       **contents,
+                     gsize        *length,
+                     GError      **error)
+{
+  gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
+  gboolean retval;
+
+  if (utf8_filename == NULL)
+    return FALSE;
+
+  retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
+
+  g_free (utf8_filename);
+
+  return retval;
+}
+
+#undef g_mkstemp
+
+gint
+g_mkstemp (gchar *tmpl)
+{
+  char *XXXXXX;
+  int count, fd;
+  static const char letters[] =
+    "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+  static const int NLETTERS = sizeof (letters) - 1;
+  glong value;
+  GTimeVal tv;
+  static int counter = 0;
+
+  /* find the last occurrence of 'XXXXXX' */
+  XXXXXX = g_strrstr (tmpl, "XXXXXX");
+
+  if (!XXXXXX)
+    {
+      errno = EINVAL;
+      return -1;
+    }
+
+  /* Get some more or less random data.  */
+  g_get_current_time (&tv);
+  value = (tv.tv_usec ^ tv.tv_sec) + counter++;
+
+  for (count = 0; count < 100; value += 7777, ++count)
+    {
+      glong v = value;
+
+      /* Fill in the random bits.  */
+      XXXXXX[0] = letters[v % NLETTERS];
+      v /= NLETTERS;
+      XXXXXX[1] = letters[v % NLETTERS];
+      v /= NLETTERS;
+      XXXXXX[2] = letters[v % NLETTERS];
+      v /= NLETTERS;
+      XXXXXX[3] = letters[v % NLETTERS];
+      v /= NLETTERS;
+      XXXXXX[4] = letters[v % NLETTERS];
+      v /= NLETTERS;
+      XXXXXX[5] = letters[v % NLETTERS];
+
+      /* This is the backward compatibility system codepage version,
+       * thus use normal open().
+       */
+      fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
+
+      if (fd >= 0)
+       return fd;
+      else if (errno != EEXIST)
+       /* Any other error will apply also to other names we might
+        *  try, and there are 2^32 or so of them, so give up now.
+        */
+       return -1;
+    }
+
+  /* We got out of the loop because we ran out of combinations to try.  */
+  errno = EEXIST;
+  return -1;
+}
+
+#undef g_file_open_tmp
+
+gint
+g_file_open_tmp (const gchar  *tmpl,
+                gchar       **name_used,
+                GError      **error)
+{
+  gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
+  gchar *utf8_name_used;
+  gint retval;
+
+  if (utf8_tmpl == NULL)
+    return -1;
+
+  retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
+  
+  if (retval == -1)
+    return -1;
+
+  if (name_used)
+    *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
+
+  g_free (utf8_name_used);
+
+  return retval;
+}
+
+#endif