Home | History | Annotate | Download | only in glib
      1 /* gfileutils.c - File utility functions
      2  *
      3  *  Copyright 2000 Red Hat, Inc.
      4  *
      5  * GLib is free software; you can redistribute it and/or modify it
      6  * under the terms of the GNU Lesser General Public License as
      7  * published by the Free Software Foundation; either version 2 of the
      8  * License, or (at your option) any later version.
      9  *
     10  * GLib is distributed in the hope that it will be useful,
     11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     13  * Lesser General Public License for more details.
     14  *
     15  * You should have received a copy of the GNU Lesser General Public
     16  * License along with GLib; see the file COPYING.LIB.  If not,
     17  * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
     18  *   Boston, MA 02111-1307, USA.
     19  */
     20 
     21 #include "config.h"
     22 
     23 #include "glib.h"
     24 
     25 #include <sys/stat.h>
     26 #ifdef HAVE_UNISTD_H
     27 #include <unistd.h>
     28 #endif
     29 #include <stdio.h>
     30 #include <stdlib.h>
     31 #include <stdarg.h>
     32 #include <string.h>
     33 #include <errno.h>
     34 #include <sys/types.h>
     35 #include <sys/stat.h>
     36 #include <fcntl.h>
     37 #include <stdlib.h>
     38 
     39 #ifdef G_OS_WIN32
     40 #include <windows.h>
     41 #include <io.h>
     42 #endif /* G_OS_WIN32 */
     43 
     44 #ifndef S_ISLNK
     45 #define S_ISLNK(x) 0
     46 #endif
     47 
     48 #ifndef O_BINARY
     49 #define O_BINARY 0
     50 #endif
     51 
     52 #include "gstdio.h"
     53 #include "glibintl.h"
     54 
     55 #include "galias.h"
     56 
     57 static gint create_temp_file (gchar *tmpl,
     58 			      int    permissions);
     59 
     60 /**
     61  * g_mkdir_with_parents:
     62  * @pathname: a pathname in the GLib file name encoding
     63  * @mode: permissions to use for newly created directories
     64  *
     65  * Create a directory if it doesn't already exist. Create intermediate
     66  * parent directories as needed, too.
     67  *
     68  * Returns: 0 if the directory already exists, or was successfully
     69  * created. Returns -1 if an error occurred, with errno set.
     70  *
     71  * Since: 2.8
     72  */
     73 int
     74 g_mkdir_with_parents (const gchar *pathname,
     75 		      int          mode)
     76 {
     77   gchar *fn, *p;
     78 
     79   if (pathname == NULL || *pathname == '\0')
     80     {
     81       errno = EINVAL;
     82       return -1;
     83     }
     84 
     85   fn = g_strdup (pathname);
     86 
     87   if (g_path_is_absolute (fn))
     88     p = (gchar *) g_path_skip_root (fn);
     89   else
     90     p = fn;
     91 
     92   do
     93     {
     94       while (*p && !G_IS_DIR_SEPARATOR (*p))
     95 	p++;
     96 
     97       if (!*p)
     98 	p = NULL;
     99       else
    100 	*p = '\0';
    101 
    102       if (!g_file_test (fn, G_FILE_TEST_EXISTS))
    103 	{
    104 	  if (g_mkdir (fn, mode) == -1)
    105 	    {
    106 	      int errno_save = errno;
    107 	      g_free (fn);
    108 	      errno = errno_save;
    109 	      return -1;
    110 	    }
    111 	}
    112       else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
    113 	{
    114 	  g_free (fn);
    115 	  errno = ENOTDIR;
    116 	  return -1;
    117 	}
    118       if (p)
    119 	{
    120 	  *p++ = G_DIR_SEPARATOR;
    121 	  while (*p && G_IS_DIR_SEPARATOR (*p))
    122 	    p++;
    123 	}
    124     }
    125   while (p);
    126 
    127   g_free (fn);
    128 
    129   return 0;
    130 }
    131 
    132 /**
    133  * g_file_test:
    134  * @filename: a filename to test in the GLib file name encoding
    135  * @test: bitfield of #GFileTest flags
    136  *
    137  * Returns %TRUE if any of the tests in the bitfield @test are
    138  * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS |
    139  * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists;
    140  * the check whether it's a directory doesn't matter since the existence
    141  * test is %TRUE. With the current set of available tests, there's no point
    142  * passing in more than one test at a time.
    143  *
    144  * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
    145  * so for a symbolic link to a regular file g_file_test() will return
    146  * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
    147  *
    148  * Note, that for a dangling symbolic link g_file_test() will return
    149  * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
    150  *
    151  * You should never use g_file_test() to test whether it is safe
    152  * to perform an operation, because there is always the possibility
    153  * of the condition changing before you actually perform the operation.
    154  * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
    155  * to know whether it is safe to write to a file without being
    156  * tricked into writing into a different location. It doesn't work!
    157  * |[
    158  * /&ast; DON'T DO THIS &ast;/
    159  *  if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
    160  *    {
    161  *      fd = g_open (filename, O_WRONLY);
    162  *      /&ast; write to fd &ast;/
    163  *    }
    164  * ]|
    165  *
    166  * Another thing to note is that %G_FILE_TEST_EXISTS and
    167  * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
    168  * system call. This usually doesn't matter, but if your program
    169  * is setuid or setgid it means that these tests will give you
    170  * the answer for the real user ID and group ID, rather than the
    171  * effective user ID and group ID.
    172  *
    173  * On Windows, there are no symlinks, so testing for
    174  * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
    175  * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
    176  * its name indicates that it is executable, checking for well-known
    177  * extensions and those listed in the %PATHEXT environment variable.
    178  *
    179  * Return value: whether a test was %TRUE
    180  **/
    181 gboolean
    182 g_file_test (const gchar *filename,
    183              GFileTest    test)
    184 {
    185 #ifdef G_OS_WIN32
    186 /* stuff missing in std vc6 api */
    187 #  ifndef INVALID_FILE_ATTRIBUTES
    188 #    define INVALID_FILE_ATTRIBUTES -1
    189 #  endif
    190 #  ifndef FILE_ATTRIBUTE_DEVICE
    191 #    define FILE_ATTRIBUTE_DEVICE 64
    192 #  endif
    193   int attributes;
    194   wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
    195 
    196   if (wfilename == NULL)
    197     return FALSE;
    198 
    199   attributes = GetFileAttributesW (wfilename);
    200 
    201   g_free (wfilename);
    202 
    203   if (attributes == INVALID_FILE_ATTRIBUTES)
    204     return FALSE;
    205 
    206   if (test & G_FILE_TEST_EXISTS)
    207     return TRUE;
    208 
    209   if (test & G_FILE_TEST_IS_REGULAR)
    210     return (attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0;
    211 
    212   if (test & G_FILE_TEST_IS_DIR)
    213     return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
    214 
    215   if (test & G_FILE_TEST_IS_EXECUTABLE)
    216     {
    217       const gchar *lastdot = strrchr (filename, '.');
    218       const gchar *pathext = NULL, *p;
    219       int extlen;
    220 
    221       if (lastdot == NULL)
    222 	return FALSE;
    223 
    224       if (_stricmp (lastdot, ".exe") == 0 ||
    225 	  _stricmp (lastdot, ".cmd") == 0 ||
    226 	  _stricmp (lastdot, ".bat") == 0 ||
    227 	  _stricmp (lastdot, ".com") == 0)
    228 	return TRUE;
    229 
    230       /* Check if it is one of the types listed in %PATHEXT% */
    231 
    232       pathext = g_getenv ("PATHEXT");
    233       if (pathext == NULL)
    234 	return FALSE;
    235 
    236       pathext = g_utf8_casefold (pathext, -1);
    237 
    238       lastdot = g_utf8_casefold (lastdot, -1);
    239       extlen = strlen (lastdot);
    240 
    241       p = pathext;
    242       while (TRUE)
    243 	{
    244 	  const gchar *q = strchr (p, ';');
    245 	  if (q == NULL)
    246 	    q = p + strlen (p);
    247 	  if (extlen == q - p &&
    248 	      memcmp (lastdot, p, extlen) == 0)
    249 	    {
    250 	      g_free ((gchar *) pathext);
    251 	      g_free ((gchar *) lastdot);
    252 	      return TRUE;
    253 	    }
    254 	  if (*q)
    255 	    p = q + 1;
    256 	  else
    257 	    break;
    258 	}
    259 
    260       g_free ((gchar *) pathext);
    261       g_free ((gchar *) lastdot);
    262       return FALSE;
    263     }
    264 
    265   return FALSE;
    266 #else
    267   if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
    268     return TRUE;
    269 
    270   if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
    271     {
    272       if (getuid () != 0)
    273 	return TRUE;
    274 
    275       /* For root, on some POSIX systems, access (filename, X_OK)
    276        * will succeed even if no executable bits are set on the
    277        * file. We fall through to a stat test to avoid that.
    278        */
    279     }
    280   else
    281     test &= ~G_FILE_TEST_IS_EXECUTABLE;
    282 
    283   if (test & G_FILE_TEST_IS_SYMLINK)
    284     {
    285       struct stat s;
    286 
    287       if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
    288         return TRUE;
    289     }
    290 
    291   if (test & (G_FILE_TEST_IS_REGULAR |
    292 	      G_FILE_TEST_IS_DIR |
    293 	      G_FILE_TEST_IS_EXECUTABLE))
    294     {
    295       struct stat s;
    296 
    297       if (stat (filename, &s) == 0)
    298 	{
    299 	  if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
    300 	    return TRUE;
    301 
    302 	  if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
    303 	    return TRUE;
    304 
    305 	  /* The extra test for root when access (file, X_OK) succeeds.
    306 	   */
    307 	  if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
    308 	      ((s.st_mode & S_IXOTH) ||
    309 	       (s.st_mode & S_IXUSR) ||
    310 	       (s.st_mode & S_IXGRP)))
    311 	    return TRUE;
    312 	}
    313     }
    314 
    315   return FALSE;
    316 #endif
    317 }
    318 
    319 GQuark
    320 g_file_error_quark (void)
    321 {
    322   return g_quark_from_static_string ("g-file-error-quark");
    323 }
    324 
    325 /**
    326  * g_file_error_from_errno:
    327  * @err_no: an "errno" value
    328  *
    329  * Gets a #GFileError constant based on the passed-in @errno.
    330  * For example, if you pass in %EEXIST this function returns
    331  * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
    332  * assume that all #GFileError values will exist.
    333  *
    334  * Normally a #GFileError value goes into a #GError returned
    335  * from a function that manipulates files. So you would use
    336  * g_file_error_from_errno() when constructing a #GError.
    337  *
    338  * Return value: #GFileError corresponding to the given @errno
    339  **/
    340 GFileError
    341 g_file_error_from_errno (gint err_no)
    342 {
    343   switch (err_no)
    344     {
    345 #ifdef EEXIST
    346     case EEXIST:
    347       return G_FILE_ERROR_EXIST;
    348       break;
    349 #endif
    350 
    351 #ifdef EISDIR
    352     case EISDIR:
    353       return G_FILE_ERROR_ISDIR;
    354       break;
    355 #endif
    356 
    357 #ifdef EACCES
    358     case EACCES:
    359       return G_FILE_ERROR_ACCES;
    360       break;
    361 #endif
    362 
    363 #ifdef ENAMETOOLONG
    364     case ENAMETOOLONG:
    365       return G_FILE_ERROR_NAMETOOLONG;
    366       break;
    367 #endif
    368 
    369 #ifdef ENOENT
    370     case ENOENT:
    371       return G_FILE_ERROR_NOENT;
    372       break;
    373 #endif
    374 
    375 #ifdef ENOTDIR
    376     case ENOTDIR:
    377       return G_FILE_ERROR_NOTDIR;
    378       break;
    379 #endif
    380 
    381 #ifdef ENXIO
    382     case ENXIO:
    383       return G_FILE_ERROR_NXIO;
    384       break;
    385 #endif
    386 
    387 #ifdef ENODEV
    388     case ENODEV:
    389       return G_FILE_ERROR_NODEV;
    390       break;
    391 #endif
    392 
    393 #ifdef EROFS
    394     case EROFS:
    395       return G_FILE_ERROR_ROFS;
    396       break;
    397 #endif
    398 
    399 #ifdef ETXTBSY
    400     case ETXTBSY:
    401       return G_FILE_ERROR_TXTBSY;
    402       break;
    403 #endif
    404 
    405 #ifdef EFAULT
    406     case EFAULT:
    407       return G_FILE_ERROR_FAULT;
    408       break;
    409 #endif
    410 
    411 #ifdef ELOOP
    412     case ELOOP:
    413       return G_FILE_ERROR_LOOP;
    414       break;
    415 #endif
    416 
    417 #ifdef ENOSPC
    418     case ENOSPC:
    419       return G_FILE_ERROR_NOSPC;
    420       break;
    421 #endif
    422 
    423 #ifdef ENOMEM
    424     case ENOMEM:
    425       return G_FILE_ERROR_NOMEM;
    426       break;
    427 #endif
    428 
    429 #ifdef EMFILE
    430     case EMFILE:
    431       return G_FILE_ERROR_MFILE;
    432       break;
    433 #endif
    434 
    435 #ifdef ENFILE
    436     case ENFILE:
    437       return G_FILE_ERROR_NFILE;
    438       break;
    439 #endif
    440 
    441 #ifdef EBADF
    442     case EBADF:
    443       return G_FILE_ERROR_BADF;
    444       break;
    445 #endif
    446 
    447 #ifdef EINVAL
    448     case EINVAL:
    449       return G_FILE_ERROR_INVAL;
    450       break;
    451 #endif
    452 
    453 #ifdef EPIPE
    454     case EPIPE:
    455       return G_FILE_ERROR_PIPE;
    456       break;
    457 #endif
    458 
    459 #ifdef EAGAIN
    460     case EAGAIN:
    461       return G_FILE_ERROR_AGAIN;
    462       break;
    463 #endif
    464 
    465 #ifdef EINTR
    466     case EINTR:
    467       return G_FILE_ERROR_INTR;
    468       break;
    469 #endif
    470 
    471 #ifdef EIO
    472     case EIO:
    473       return G_FILE_ERROR_IO;
    474       break;
    475 #endif
    476 
    477 #ifdef EPERM
    478     case EPERM:
    479       return G_FILE_ERROR_PERM;
    480       break;
    481 #endif
    482 
    483 #ifdef ENOSYS
    484     case ENOSYS:
    485       return G_FILE_ERROR_NOSYS;
    486       break;
    487 #endif
    488 
    489     default:
    490       return G_FILE_ERROR_FAILED;
    491       break;
    492     }
    493 }
    494 
    495 static gboolean
    496 get_contents_stdio (const gchar  *display_filename,
    497                     FILE         *f,
    498                     gchar       **contents,
    499                     gsize        *length,
    500                     GError      **error)
    501 {
    502   gchar buf[4096];
    503   gsize bytes;
    504   gchar *str = NULL;
    505   gsize total_bytes = 0;
    506   gsize total_allocated = 0;
    507   gchar *tmp;
    508 
    509   g_assert (f != NULL);
    510 
    511   while (!feof (f))
    512     {
    513       gint save_errno;
    514 
    515       bytes = fread (buf, 1, sizeof (buf), f);
    516       save_errno = errno;
    517 
    518       while ((total_bytes + bytes + 1) > total_allocated)
    519         {
    520           if (str)
    521             total_allocated *= 2;
    522           else
    523             total_allocated = MIN (bytes + 1, sizeof (buf));
    524 
    525           tmp = g_try_realloc (str, total_allocated);
    526 
    527           if (tmp == NULL)
    528             {
    529               g_set_error (error,
    530                            G_FILE_ERROR,
    531                            G_FILE_ERROR_NOMEM,
    532                            _("Could not allocate %lu bytes to read file \"%s\""),
    533                            (gulong) total_allocated,
    534 			   display_filename);
    535 
    536               goto error;
    537             }
    538 
    539 	  str = tmp;
    540         }
    541 
    542       if (ferror (f))
    543         {
    544           g_set_error (error,
    545                        G_FILE_ERROR,
    546                        g_file_error_from_errno (save_errno),
    547                        _("Error reading file '%s': %s"),
    548                        display_filename,
    549 		       g_strerror (save_errno));
    550 
    551           goto error;
    552         }
    553 
    554       memcpy (str + total_bytes, buf, bytes);
    555 
    556       if (total_bytes + bytes < total_bytes)
    557         {
    558           g_set_error (error,
    559                        G_FILE_ERROR,
    560                        G_FILE_ERROR_FAILED,
    561                        _("File \"%s\" is too large"),
    562                        display_filename);
    563 
    564           goto error;
    565         }
    566 
    567       total_bytes += bytes;
    568     }
    569 
    570   fclose (f);
    571 
    572   if (total_allocated == 0)
    573     {
    574       str = g_new (gchar, 1);
    575       total_bytes = 0;
    576     }
    577 
    578   str[total_bytes] = '\0';
    579 
    580   if (length)
    581     *length = total_bytes;
    582 
    583   *contents = str;
    584 
    585   return TRUE;
    586 
    587  error:
    588 
    589   g_free (str);
    590   fclose (f);
    591 
    592   return FALSE;
    593 }
    594 
    595 #ifndef G_OS_WIN32
    596 
    597 static gboolean
    598 get_contents_regfile (const gchar  *display_filename,
    599                       struct stat  *stat_buf,
    600                       gint          fd,
    601                       gchar       **contents,
    602                       gsize        *length,
    603                       GError      **error)
    604 {
    605   gchar *buf;
    606   gsize bytes_read;
    607   gsize size;
    608   gsize alloc_size;
    609 
    610   size = stat_buf->st_size;
    611 
    612   alloc_size = size + 1;
    613   buf = g_try_malloc (alloc_size);
    614 
    615   if (buf == NULL)
    616     {
    617       g_set_error (error,
    618                    G_FILE_ERROR,
    619                    G_FILE_ERROR_NOMEM,
    620                    _("Could not allocate %lu bytes to read file \"%s\""),
    621                    (gulong) alloc_size,
    622 		   display_filename);
    623 
    624       goto error;
    625     }
    626 
    627   bytes_read = 0;
    628   while (bytes_read < size)
    629     {
    630       gssize rc;
    631 
    632       rc = read (fd, buf + bytes_read, size - bytes_read);
    633 
    634       if (rc < 0)
    635         {
    636           if (errno != EINTR)
    637             {
    638 	      int save_errno = errno;
    639 
    640               g_free (buf);
    641               g_set_error (error,
    642                            G_FILE_ERROR,
    643                            g_file_error_from_errno (save_errno),
    644                            _("Failed to read from file '%s': %s"),
    645                            display_filename,
    646 			   g_strerror (save_errno));
    647 
    648 	      goto error;
    649             }
    650         }
    651       else if (rc == 0)
    652         break;
    653       else
    654         bytes_read += rc;
    655     }
    656 
    657   buf[bytes_read] = '\0';
    658 
    659   if (length)
    660     *length = bytes_read;
    661 
    662   *contents = buf;
    663 
    664   close (fd);
    665 
    666   return TRUE;
    667 
    668  error:
    669 
    670   close (fd);
    671 
    672   return FALSE;
    673 }
    674 
    675 static gboolean
    676 get_contents_posix (const gchar  *filename,
    677                     gchar       **contents,
    678                     gsize        *length,
    679                     GError      **error)
    680 {
    681   struct stat stat_buf;
    682   gint fd;
    683   gchar *display_filename = g_filename_display_name (filename);
    684 
    685   /* O_BINARY useful on Cygwin */
    686   fd = open (filename, O_RDONLY|O_BINARY);
    687 
    688   if (fd < 0)
    689     {
    690       int save_errno = errno;
    691 
    692       g_set_error (error,
    693                    G_FILE_ERROR,
    694                    g_file_error_from_errno (save_errno),
    695                    _("Failed to open file '%s': %s"),
    696                    display_filename,
    697 		   g_strerror (save_errno));
    698       g_free (display_filename);
    699 
    700       return FALSE;
    701     }
    702 
    703   /* I don't think this will ever fail, aside from ENOMEM, but. */
    704   if (fstat (fd, &stat_buf) < 0)
    705     {
    706       int save_errno = errno;
    707 
    708       close (fd);
    709       g_set_error (error,
    710                    G_FILE_ERROR,
    711                    g_file_error_from_errno (save_errno),
    712                    _("Failed to get attributes of file '%s': fstat() failed: %s"),
    713                    display_filename,
    714 		   g_strerror (save_errno));
    715       g_free (display_filename);
    716 
    717       return FALSE;
    718     }
    719 
    720   if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
    721     {
    722       gboolean retval = get_contents_regfile (display_filename,
    723 					      &stat_buf,
    724 					      fd,
    725 					      contents,
    726 					      length,
    727 					      error);
    728       g_free (display_filename);
    729 
    730       return retval;
    731     }
    732   else
    733     {
    734       FILE *f;
    735       gboolean retval;
    736 
    737       f = fdopen (fd, "r");
    738 
    739       if (f == NULL)
    740         {
    741 	  int save_errno = errno;
    742 
    743           g_set_error (error,
    744                        G_FILE_ERROR,
    745                        g_file_error_from_errno (save_errno),
    746                        _("Failed to open file '%s': fdopen() failed: %s"),
    747                        display_filename,
    748 		       g_strerror (save_errno));
    749           g_free (display_filename);
    750 
    751           return FALSE;
    752         }
    753 
    754       retval = get_contents_stdio (display_filename, f, contents, length, error);
    755       g_free (display_filename);
    756 
    757       return retval;
    758     }
    759 }
    760 
    761 #else  /* G_OS_WIN32 */
    762 
    763 static gboolean
    764 get_contents_win32 (const gchar  *filename,
    765 		    gchar       **contents,
    766 		    gsize        *length,
    767 		    GError      **error)
    768 {
    769   FILE *f;
    770   gboolean retval;
    771   gchar *display_filename = g_filename_display_name (filename);
    772   int save_errno;
    773 
    774   f = g_fopen (filename, "rb");
    775   save_errno = errno;
    776 
    777   if (f == NULL)
    778     {
    779       g_set_error (error,
    780                    G_FILE_ERROR,
    781                    g_file_error_from_errno (save_errno),
    782                    _("Failed to open file '%s': %s"),
    783                    display_filename,
    784 		   g_strerror (save_errno));
    785       g_free (display_filename);
    786 
    787       return FALSE;
    788     }
    789 
    790   retval = get_contents_stdio (display_filename, f, contents, length, error);
    791   g_free (display_filename);
    792 
    793   return retval;
    794 }
    795 
    796 #endif
    797 
    798 /**
    799  * g_file_get_contents:
    800  * @filename: name of a file to read contents from, in the GLib file name encoding
    801  * @contents: location to store an allocated string, use g_free() to free
    802  *     the returned string
    803  * @length: location to store length in bytes of the contents, or %NULL
    804  * @error: return location for a #GError, or %NULL
    805  *
    806  * Reads an entire file into allocated memory, with good error
    807  * checking.
    808  *
    809  * If the call was successful, it returns %TRUE and sets @contents to the file
    810  * contents and @length to the length of the file contents in bytes. The string
    811  * stored in @contents will be nul-terminated, so for text files you can pass
    812  * %NULL for the @length argument. If the call was not successful, it returns
    813  * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
    814  * codes are those in the #GFileError enumeration. In the error case,
    815  * @contents is set to %NULL and @length is set to zero.
    816  *
    817  * Return value: %TRUE on success, %FALSE if an error occurred
    818  **/
    819 gboolean
    820 g_file_get_contents (const gchar  *filename,
    821                      gchar       **contents,
    822                      gsize        *length,
    823                      GError      **error)
    824 {
    825   g_return_val_if_fail (filename != NULL, FALSE);
    826   g_return_val_if_fail (contents != NULL, FALSE);
    827 
    828   *contents = NULL;
    829   if (length)
    830     *length = 0;
    831 
    832 #ifdef G_OS_WIN32
    833   return get_contents_win32 (filename, contents, length, error);
    834 #else
    835   return get_contents_posix (filename, contents, length, error);
    836 #endif
    837 }
    838 
    839 static gboolean
    840 rename_file (const char  *old_name,
    841 	     const char  *new_name,
    842 	     GError     **err)
    843 {
    844   errno = 0;
    845   if (g_rename (old_name, new_name) == -1)
    846     {
    847       int save_errno = errno;
    848       gchar *display_old_name = g_filename_display_name (old_name);
    849       gchar *display_new_name = g_filename_display_name (new_name);
    850 
    851       g_set_error (err,
    852 		   G_FILE_ERROR,
    853 		   g_file_error_from_errno (save_errno),
    854 		   _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
    855 		   display_old_name,
    856 		   display_new_name,
    857 		   g_strerror (save_errno));
    858 
    859       g_free (display_old_name);
    860       g_free (display_new_name);
    861 
    862       return FALSE;
    863     }
    864 
    865   return TRUE;
    866 }
    867 
    868 static gchar *
    869 write_to_temp_file (const gchar  *contents,
    870 		    gssize        length,
    871 		    const gchar  *dest_file,
    872 		    GError      **err)
    873 {
    874   gchar *tmp_name;
    875   gchar *display_name;
    876   gchar *retval;
    877   FILE *file;
    878   gint fd;
    879   int save_errno;
    880 
    881   retval = NULL;
    882 
    883   tmp_name = g_strdup_printf ("%s.XXXXXX", dest_file);
    884 
    885   errno = 0;
    886   fd = create_temp_file (tmp_name, 0666);
    887   save_errno = errno;
    888 
    889   display_name = g_filename_display_name (tmp_name);
    890 
    891   if (fd == -1)
    892     {
    893       g_set_error (err,
    894 		   G_FILE_ERROR,
    895 		   g_file_error_from_errno (save_errno),
    896 		   _("Failed to create file '%s': %s"),
    897 		   display_name, g_strerror (save_errno));
    898 
    899       goto out;
    900     }
    901 
    902   errno = 0;
    903   file = fdopen (fd, "wb");
    904   if (!file)
    905     {
    906       save_errno = errno;
    907       g_set_error (err,
    908 		   G_FILE_ERROR,
    909 		   g_file_error_from_errno (save_errno),
    910 		   _("Failed to open file '%s' for writing: fdopen() failed: %s"),
    911 		   display_name,
    912 		   g_strerror (save_errno));
    913 
    914       close (fd);
    915       g_unlink (tmp_name);
    916 
    917       goto out;
    918     }
    919 
    920   if (length > 0)
    921     {
    922       gsize n_written;
    923 
    924       errno = 0;
    925 
    926       n_written = fwrite (contents, 1, length, file);
    927 
    928       if (n_written < length)
    929 	{
    930 	  save_errno = errno;
    931 
    932  	  g_set_error (err,
    933 		       G_FILE_ERROR,
    934 		       g_file_error_from_errno (save_errno),
    935 		       _("Failed to write file '%s': fwrite() failed: %s"),
    936 		       display_name,
    937 		       g_strerror (save_errno));
    938 
    939 	  fclose (file);
    940 	  g_unlink (tmp_name);
    941 
    942 	  goto out;
    943 	}
    944     }
    945 
    946   errno = 0;
    947   if (fflush (file) != 0)
    948     {
    949       save_errno = errno;
    950 
    951       g_set_error (err,
    952 		   G_FILE_ERROR,
    953 		   g_file_error_from_errno (save_errno),
    954 		   _("Failed to write file '%s': fflush() failed: %s"),
    955 		   display_name,
    956 		   g_strerror (save_errno));
    957 
    958       g_unlink (tmp_name);
    959 
    960       goto out;
    961     }
    962 
    963 #ifdef HAVE_FSYNC
    964   errno = 0;
    965   /* If the final destination exists, we want to sync the newly written
    966    * file to ensure the data is on disk when we rename over the destination.
    967    * otherwise if we get a system crash we can lose both the new and the
    968    * old file on some filesystems. (I.E. those that don't guarantee the
    969    * data is written to the disk before the metadata.)
    970    */
    971   if (g_file_test (dest_file, G_FILE_TEST_EXISTS) &&
    972       fsync (fileno (file)) != 0)
    973     {
    974       save_errno = errno;
    975 
    976       g_set_error (err,
    977 		   G_FILE_ERROR,
    978 		   g_file_error_from_errno (save_errno),
    979 		   _("Failed to write file '%s': fsync() failed: %s"),
    980 		   display_name,
    981 		   g_strerror (save_errno));
    982 
    983       g_unlink (tmp_name);
    984 
    985       goto out;
    986     }
    987 #endif
    988 
    989   errno = 0;
    990   if (fclose (file) == EOF)
    991     {
    992       save_errno = errno;
    993 
    994       g_set_error (err,
    995 		   G_FILE_ERROR,
    996 		   g_file_error_from_errno (save_errno),
    997 		   _("Failed to close file '%s': fclose() failed: %s"),
    998 		   display_name,
    999 		   g_strerror (save_errno));
   1000 
   1001       g_unlink (tmp_name);
   1002 
   1003       goto out;
   1004     }
   1005 
   1006   retval = g_strdup (tmp_name);
   1007 
   1008  out:
   1009   g_free (tmp_name);
   1010   g_free (display_name);
   1011 
   1012   return retval;
   1013 }
   1014 
   1015 /**
   1016  * g_file_set_contents:
   1017  * @filename: name of a file to write @contents to, in the GLib file name
   1018  *   encoding
   1019  * @contents: string to write to the file
   1020  * @length: length of @contents, or -1 if @contents is a nul-terminated string
   1021  * @error: return location for a #GError, or %NULL
   1022  *
   1023  * Writes all of @contents to a file named @filename, with good error checking.
   1024  * If a file called @filename already exists it will be overwritten.
   1025  *
   1026  * This write is atomic in the sense that it is first written to a temporary
   1027  * file which is then renamed to the final name. Notes:
   1028  * <itemizedlist>
   1029  * <listitem>
   1030  *    On Unix, if @filename already exists hard links to @filename will break.
   1031  *    Also since the file is recreated, existing permissions, access control
   1032  *    lists, metadata etc. may be lost. If @filename is a symbolic link,
   1033  *    the link itself will be replaced, not the linked file.
   1034  * </listitem>
   1035  * <listitem>
   1036  *   On Windows renaming a file will not remove an existing file with the
   1037  *   new name, so on Windows there is a race condition between the existing
   1038  *   file being removed and the temporary file being renamed.
   1039  * </listitem>
   1040  * <listitem>
   1041  *   On Windows there is no way to remove a file that is open to some
   1042  *   process, or mapped into memory. Thus, this function will fail if
   1043  *   @filename already exists and is open.
   1044  * </listitem>
   1045  * </itemizedlist>
   1046  *
   1047  * If the call was sucessful, it returns %TRUE. If the call was not successful,
   1048  * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
   1049  * Possible error codes are those in the #GFileError enumeration.
   1050  *
   1051  * Return value: %TRUE on success, %FALSE if an error occurred
   1052  *
   1053  * Since: 2.8
   1054  **/
   1055 gboolean
   1056 g_file_set_contents (const gchar  *filename,
   1057 		     const gchar  *contents,
   1058 		     gssize	   length,
   1059 		     GError	 **error)
   1060 {
   1061   gchar *tmp_filename;
   1062   gboolean retval;
   1063   GError *rename_error = NULL;
   1064 
   1065   g_return_val_if_fail (filename != NULL, FALSE);
   1066   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
   1067   g_return_val_if_fail (contents != NULL || length == 0, FALSE);
   1068   g_return_val_if_fail (length >= -1, FALSE);
   1069 
   1070   if (length == -1)
   1071     length = strlen (contents);
   1072 
   1073   tmp_filename = write_to_temp_file (contents, length, filename, error);
   1074 
   1075   if (!tmp_filename)
   1076     {
   1077       retval = FALSE;
   1078       goto out;
   1079     }
   1080 
   1081   if (!rename_file (tmp_filename, filename, &rename_error))
   1082     {
   1083 #ifndef G_OS_WIN32
   1084 
   1085       g_unlink (tmp_filename);
   1086       g_propagate_error (error, rename_error);
   1087       retval = FALSE;
   1088       goto out;
   1089 
   1090 #else /* G_OS_WIN32 */
   1091 
   1092       /* Renaming failed, but on Windows this may just mean
   1093        * the file already exists. So if the target file
   1094        * exists, try deleting it and do the rename again.
   1095        */
   1096       if (!g_file_test (filename, G_FILE_TEST_EXISTS))
   1097 	{
   1098 	  g_unlink (tmp_filename);
   1099 	  g_propagate_error (error, rename_error);
   1100 	  retval = FALSE;
   1101 	  goto out;
   1102 	}
   1103 
   1104       g_error_free (rename_error);
   1105 
   1106       if (g_unlink (filename) == -1)
   1107 	{
   1108           gchar *display_filename = g_filename_display_name (filename);
   1109 
   1110 	  int save_errno = errno;
   1111 
   1112 	  g_set_error (error,
   1113 		       G_FILE_ERROR,
   1114 		       g_file_error_from_errno (save_errno),
   1115 		       _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
   1116 		       display_filename,
   1117 		       g_strerror (save_errno));
   1118 
   1119 	  g_free (display_filename);
   1120 	  g_unlink (tmp_filename);
   1121 	  retval = FALSE;
   1122 	  goto out;
   1123 	}
   1124 
   1125       if (!rename_file (tmp_filename, filename, error))
   1126 	{
   1127 	  g_unlink (tmp_filename);
   1128 	  retval = FALSE;
   1129 	  goto out;
   1130 	}
   1131 
   1132 #endif
   1133     }
   1134 
   1135   retval = TRUE;
   1136 
   1137  out:
   1138   g_free (tmp_filename);
   1139   return retval;
   1140 }
   1141 
   1142 /*
   1143  * create_temp_file based on the mkstemp implementation from the GNU C library.
   1144  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
   1145  */
   1146 static gint
   1147 create_temp_file (gchar *tmpl,
   1148 		  int    permissions)
   1149 {
   1150   char *XXXXXX;
   1151   int count, fd;
   1152   static const char letters[] =
   1153     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   1154   static const int NLETTERS = sizeof (letters) - 1;
   1155   glong value;
   1156   GTimeVal tv;
   1157   static int counter = 0;
   1158 
   1159   /* find the last occurrence of "XXXXXX" */
   1160   XXXXXX = g_strrstr (tmpl, "XXXXXX");
   1161 
   1162   if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
   1163     {
   1164       errno = EINVAL;
   1165       return -1;
   1166     }
   1167 
   1168   /* Get some more or less random data.  */
   1169   g_get_current_time (&tv);
   1170   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
   1171 
   1172   for (count = 0; count < 100; value += 7777, ++count)
   1173     {
   1174       glong v = value;
   1175 
   1176       /* Fill in the random bits.  */
   1177       XXXXXX[0] = letters[v % NLETTERS];
   1178       v /= NLETTERS;
   1179       XXXXXX[1] = letters[v % NLETTERS];
   1180       v /= NLETTERS;
   1181       XXXXXX[2] = letters[v % NLETTERS];
   1182       v /= NLETTERS;
   1183       XXXXXX[3] = letters[v % NLETTERS];
   1184       v /= NLETTERS;
   1185       XXXXXX[4] = letters[v % NLETTERS];
   1186       v /= NLETTERS;
   1187       XXXXXX[5] = letters[v % NLETTERS];
   1188 
   1189       /* tmpl is in UTF-8 on Windows, thus use g_open() */
   1190       fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, permissions);
   1191 
   1192       if (fd >= 0)
   1193 	return fd;
   1194       else if (errno != EEXIST)
   1195 	/* Any other error will apply also to other names we might
   1196 	 *  try, and there are 2^32 or so of them, so give up now.
   1197 	 */
   1198 	return -1;
   1199     }
   1200 
   1201   /* We got out of the loop because we ran out of combinations to try.  */
   1202   errno = EEXIST;
   1203   return -1;
   1204 }
   1205 
   1206 /**
   1207  * g_mkstemp:
   1208  * @tmpl: template filename
   1209  *
   1210  * Opens a temporary file. See the mkstemp() documentation
   1211  * on most UNIX-like systems.
   1212  *
   1213  * The parameter is a string that should follow the rules for
   1214  * mkstemp() templates, i.e. contain the string "XXXXXX".
   1215  * g_mkstemp() is slightly more flexible than mkstemp()
   1216  * in that the sequence does not have to occur at the very end of the
   1217  * template. The X string will
   1218  * be modified to form the name of a file that didn't exist.
   1219  * The string should be in the GLib file name encoding. Most importantly,
   1220  * on Windows it should be in UTF-8.
   1221  *
   1222  * Return value: A file handle (as from open()) to the file
   1223  * opened for reading and writing. The file is opened in binary mode
   1224  * on platforms where there is a difference. The file handle should be
   1225  * closed with close(). In case of errors, -1 is returned.
   1226  */
   1227 gint
   1228 g_mkstemp (gchar *tmpl)
   1229 {
   1230   return create_temp_file (tmpl, 0600);
   1231 }
   1232 
   1233 /**
   1234  * g_file_open_tmp:
   1235  * @tmpl: Template for file name, as in g_mkstemp(), basename only,
   1236  *        or %NULL, to a default template
   1237  * @name_used: location to store actual name used, or %NULL
   1238  * @error: return location for a #GError
   1239  *
   1240  * Opens a file for writing in the preferred directory for temporary
   1241  * files (as returned by g_get_tmp_dir()).
   1242  *
   1243  * @tmpl should be a string in the GLib file name encoding containing
   1244  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
   1245  * However, unlike these functions, the template should only be a
   1246  * basename, no directory components are allowed. If template is
   1247  * %NULL, a default template is used.
   1248  *
   1249  * Note that in contrast to g_mkstemp() (and mkstemp())
   1250  * @tmpl is not modified, and might thus be a read-only literal string.
   1251  *
   1252  * The actual name used is returned in @name_used if non-%NULL. This
   1253  * string should be freed with g_free() when not needed any longer.
   1254  * The returned name is in the GLib file name encoding.
   1255  *
   1256  * Return value: A file handle (as from open()) to
   1257  * the file opened for reading and writing. The file is opened in binary
   1258  * mode on platforms where there is a difference. The file handle should be
   1259  * closed with close(). In case of errors, -1 is returned
   1260  * and @error will be set.
   1261  **/
   1262 gint
   1263 g_file_open_tmp (const gchar  *tmpl,
   1264 		 gchar       **name_used,
   1265 		 GError      **error)
   1266 {
   1267   int retval;
   1268   const char *tmpdir;
   1269   const char *sep;
   1270   char *fulltemplate;
   1271   const char *slash;
   1272 
   1273   if (tmpl == NULL)
   1274     tmpl = ".XXXXXX";
   1275 
   1276   if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
   1277 #ifdef G_OS_WIN32
   1278       || (strchr (tmpl, '/') != NULL && (slash = "/"))
   1279 #endif
   1280       )
   1281     {
   1282       gchar *display_tmpl = g_filename_display_name (tmpl);
   1283       char c[2];
   1284       c[0] = *slash;
   1285       c[1] = '\0';
   1286 
   1287       g_set_error (error,
   1288 		   G_FILE_ERROR,
   1289 		   G_FILE_ERROR_FAILED,
   1290 		   _("Template '%s' invalid, should not contain a '%s'"),
   1291 		   display_tmpl, c);
   1292       g_free (display_tmpl);
   1293 
   1294       return -1;
   1295     }
   1296 
   1297   if (strstr (tmpl, "XXXXXX") == NULL)
   1298     {
   1299       gchar *display_tmpl = g_filename_display_name (tmpl);
   1300       g_set_error (error,
   1301 		   G_FILE_ERROR,
   1302 		   G_FILE_ERROR_FAILED,
   1303 		   _("Template '%s' doesn't contain XXXXXX"),
   1304 		   display_tmpl);
   1305       g_free (display_tmpl);
   1306       return -1;
   1307     }
   1308 
   1309   tmpdir = g_get_tmp_dir ();
   1310 
   1311   if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
   1312     sep = "";
   1313   else
   1314     sep = G_DIR_SEPARATOR_S;
   1315 
   1316   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
   1317 
   1318   retval = g_mkstemp (fulltemplate);
   1319 
   1320   if (retval == -1)
   1321     {
   1322       int save_errno = errno;
   1323       gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
   1324 
   1325       g_set_error (error,
   1326 		   G_FILE_ERROR,
   1327 		   g_file_error_from_errno (save_errno),
   1328 		   _("Failed to create file '%s': %s"),
   1329 		   display_fulltemplate, g_strerror (save_errno));
   1330       g_free (display_fulltemplate);
   1331       g_free (fulltemplate);
   1332       return -1;
   1333     }
   1334 
   1335   if (name_used)
   1336     *name_used = fulltemplate;
   1337   else
   1338     g_free (fulltemplate);
   1339 
   1340   return retval;
   1341 }
   1342 
   1343 static gchar *
   1344 g_build_path_va (const gchar  *separator,
   1345 		 const gchar  *first_element,
   1346 		 va_list      *args,
   1347 		 gchar       **str_array)
   1348 {
   1349   GString *result;
   1350   gint separator_len = strlen (separator);
   1351   gboolean is_first = TRUE;
   1352   gboolean have_leading = FALSE;
   1353   const gchar *single_element = NULL;
   1354   const gchar *next_element;
   1355   const gchar *last_trailing = NULL;
   1356   gint i = 0;
   1357 
   1358   result = g_string_new (NULL);
   1359 
   1360   if (str_array)
   1361     next_element = str_array[i++];
   1362   else
   1363     next_element = first_element;
   1364 
   1365   while (TRUE)
   1366     {
   1367       const gchar *element;
   1368       const gchar *start;
   1369       const gchar *end;
   1370 
   1371       if (next_element)
   1372 	{
   1373 	  element = next_element;
   1374 	  if (str_array)
   1375 	    next_element = str_array[i++];
   1376 	  else
   1377 	    next_element = va_arg (*args, gchar *);
   1378 	}
   1379       else
   1380 	break;
   1381 
   1382       /* Ignore empty elements */
   1383       if (!*element)
   1384 	continue;
   1385 
   1386       start = element;
   1387 
   1388       if (separator_len)
   1389 	{
   1390 	  while (start &&
   1391 		 strncmp (start, separator, separator_len) == 0)
   1392 	    start += separator_len;
   1393       	}
   1394 
   1395       end = start + strlen (start);
   1396 
   1397       if (separator_len)
   1398 	{
   1399 	  while (end >= start + separator_len &&
   1400 		 strncmp (end - separator_len, separator, separator_len) == 0)
   1401 	    end -= separator_len;
   1402 
   1403 	  last_trailing = end;
   1404 	  while (last_trailing >= element + separator_len &&
   1405 		 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
   1406 	    last_trailing -= separator_len;
   1407 
   1408 	  if (!have_leading)
   1409 	    {
   1410 	      /* If the leading and trailing separator strings are in the
   1411 	       * same element and overlap, the result is exactly that element
   1412 	       */
   1413 	      if (last_trailing <= start)
   1414 		single_element = element;
   1415 
   1416 	      g_string_append_len (result, element, start - element);
   1417 	      have_leading = TRUE;
   1418 	    }
   1419 	  else
   1420 	    single_element = NULL;
   1421 	}
   1422 
   1423       if (end == start)
   1424 	continue;
   1425 
   1426       if (!is_first)
   1427 	g_string_append (result, separator);
   1428 
   1429       g_string_append_len (result, start, end - start);
   1430       is_first = FALSE;
   1431     }
   1432 
   1433   if (single_element)
   1434     {
   1435       g_string_free (result, TRUE);
   1436       return g_strdup (single_element);
   1437     }
   1438   else
   1439     {
   1440       if (last_trailing)
   1441 	g_string_append (result, last_trailing);
   1442 
   1443       return g_string_free (result, FALSE);
   1444     }
   1445 }
   1446 
   1447 /**
   1448  * g_build_pathv:
   1449  * @separator: a string used to separator the elements of the path.
   1450  * @args: %NULL-terminated array of strings containing the path elements.
   1451  *
   1452  * Behaves exactly like g_build_path(), but takes the path elements
   1453  * as a string array, instead of varargs. This function is mainly
   1454  * meant for language bindings.
   1455  *
   1456  * Return value: a newly-allocated string that must be freed with g_free().
   1457  *
   1458  * Since: 2.8
   1459  */
   1460 gchar *
   1461 g_build_pathv (const gchar  *separator,
   1462 	       gchar       **args)
   1463 {
   1464   if (!args)
   1465     return NULL;
   1466 
   1467   return g_build_path_va (separator, NULL, NULL, args);
   1468 }
   1469 
   1470 
   1471 /**
   1472  * g_build_path:
   1473  * @separator: a string used to separator the elements of the path.
   1474  * @first_element: the first element in the path
   1475  * @Varargs: remaining elements in path, terminated by %NULL
   1476  *
   1477  * Creates a path from a series of elements using @separator as the
   1478  * separator between elements. At the boundary between two elements,
   1479  * any trailing occurrences of separator in the first element, or
   1480  * leading occurrences of separator in the second element are removed
   1481  * and exactly one copy of the separator is inserted.
   1482  *
   1483  * Empty elements are ignored.
   1484  *
   1485  * The number of leading copies of the separator on the result is
   1486  * the same as the number of leading copies of the separator on
   1487  * the first non-empty element.
   1488  *
   1489  * The number of trailing copies of the separator on the result is
   1490  * the same as the number of trailing copies of the separator on
   1491  * the last non-empty element. (Determination of the number of
   1492  * trailing copies is done without stripping leading copies, so
   1493  * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
   1494  * has 1 trailing copy.)
   1495  *
   1496  * However, if there is only a single non-empty element, and there
   1497  * are no characters in that element not part of the leading or
   1498  * trailing separators, then the result is exactly the original value
   1499  * of that element.
   1500  *
   1501  * Other than for determination of the number of leading and trailing
   1502  * copies of the separator, elements consisting only of copies
   1503  * of the separator are ignored.
   1504  *
   1505  * Return value: a newly-allocated string that must be freed with g_free().
   1506  **/
   1507 gchar *
   1508 g_build_path (const gchar *separator,
   1509 	      const gchar *first_element,
   1510 	      ...)
   1511 {
   1512   gchar *str;
   1513   va_list args;
   1514 
   1515   g_return_val_if_fail (separator != NULL, NULL);
   1516 
   1517   va_start (args, first_element);
   1518   str = g_build_path_va (separator, first_element, &args, NULL);
   1519   va_end (args);
   1520 
   1521   return str;
   1522 }
   1523 
   1524 #ifdef G_OS_WIN32
   1525 
   1526 static gchar *
   1527 g_build_pathname_va (const gchar  *first_element,
   1528 		     va_list      *args,
   1529 		     gchar       **str_array)
   1530 {
   1531   /* Code copied from g_build_pathv(), and modified to use two
   1532    * alternative single-character separators.
   1533    */
   1534   GString *result;
   1535   gboolean is_first = TRUE;
   1536   gboolean have_leading = FALSE;
   1537   const gchar *single_element = NULL;
   1538   const gchar *next_element;
   1539   const gchar *last_trailing = NULL;
   1540   gchar current_separator = '\\';
   1541   gint i = 0;
   1542 
   1543   result = g_string_new (NULL);
   1544 
   1545   if (str_array)
   1546     next_element = str_array[i++];
   1547   else
   1548     next_element = first_element;
   1549 
   1550   while (TRUE)
   1551     {
   1552       const gchar *element;
   1553       const gchar *start;
   1554       const gchar *end;
   1555 
   1556       if (next_element)
   1557 	{
   1558 	  element = next_element;
   1559 	  if (str_array)
   1560 	    next_element = str_array[i++];
   1561 	  else
   1562 	    next_element = va_arg (*args, gchar *);
   1563 	}
   1564       else
   1565 	break;
   1566 
   1567       /* Ignore empty elements */
   1568       if (!*element)
   1569 	continue;
   1570 
   1571       start = element;
   1572 
   1573       if (TRUE)
   1574 	{
   1575 	  while (start &&
   1576 		 (*start == '\\' || *start == '/'))
   1577 	    {
   1578 	      current_separator = *start;
   1579 	      start++;
   1580 	    }
   1581 	}
   1582 
   1583       end = start + strlen (start);
   1584 
   1585       if (TRUE)
   1586 	{
   1587 	  while (end >= start + 1 &&
   1588 		 (end[-1] == '\\' || end[-1] == '/'))
   1589 	    {
   1590 	      current_separator = end[-1];
   1591 	      end--;
   1592 	    }
   1593 
   1594 	  last_trailing = end;
   1595 	  while (last_trailing >= element + 1 &&
   1596 		 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
   1597 	    last_trailing--;
   1598 
   1599 	  if (!have_leading)
   1600 	    {
   1601 	      /* If the leading and trailing separator strings are in the
   1602 	       * same element and overlap, the result is exactly that element
   1603 	       */
   1604 	      if (last_trailing <= start)
   1605 		single_element = element;
   1606 
   1607 	      g_string_append_len (result, element, start - element);
   1608 	      have_leading = TRUE;
   1609 	    }
   1610 	  else
   1611 	    single_element = NULL;
   1612 	}
   1613 
   1614       if (end == start)
   1615 	continue;
   1616 
   1617       if (!is_first)
   1618 	g_string_append_len (result, &current_separator, 1);
   1619 
   1620       g_string_append_len (result, start, end - start);
   1621       is_first = FALSE;
   1622     }
   1623 
   1624   if (single_element)
   1625     {
   1626       g_string_free (result, TRUE);
   1627       return g_strdup (single_element);
   1628     }
   1629   else
   1630     {
   1631       if (last_trailing)
   1632 	g_string_append (result, last_trailing);
   1633 
   1634       return g_string_free (result, FALSE);
   1635     }
   1636 }
   1637 
   1638 #endif
   1639 
   1640 /**
   1641  * g_build_filenamev:
   1642  * @args: %NULL-terminated array of strings containing the path elements.
   1643  *
   1644  * Behaves exactly like g_build_filename(), but takes the path elements
   1645  * as a string array, instead of varargs. This function is mainly
   1646  * meant for language bindings.
   1647  *
   1648  * Return value: a newly-allocated string that must be freed with g_free().
   1649  *
   1650  * Since: 2.8
   1651  */
   1652 gchar *
   1653 g_build_filenamev (gchar **args)
   1654 {
   1655   gchar *str;
   1656 
   1657 #ifndef G_OS_WIN32
   1658   str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
   1659 #else
   1660   str = g_build_pathname_va (NULL, NULL, args);
   1661 #endif
   1662 
   1663   return str;
   1664 }
   1665 
   1666 /**
   1667  * g_build_filename:
   1668  * @first_element: the first element in the path
   1669  * @Varargs: remaining elements in path, terminated by %NULL
   1670  *
   1671  * Creates a filename from a series of elements using the correct
   1672  * separator for filenames.
   1673  *
   1674  * On Unix, this function behaves identically to <literal>g_build_path
   1675  * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
   1676  *
   1677  * On Windows, it takes into account that either the backslash
   1678  * (<literal>\</literal> or slash (<literal>/</literal>) can be used
   1679  * as separator in filenames, but otherwise behaves as on Unix. When
   1680  * file pathname separators need to be inserted, the one that last
   1681  * previously occurred in the parameters (reading from left to right)
   1682  * is used.
   1683  *
   1684  * No attempt is made to force the resulting filename to be an absolute
   1685  * path. If the first element is a relative path, the result will
   1686  * be a relative path.
   1687  *
   1688  * Return value: a newly-allocated string that must be freed with g_free().
   1689  **/
   1690 gchar *
   1691 g_build_filename (const gchar *first_element,
   1692 		  ...)
   1693 {
   1694   gchar *str;
   1695   va_list args;
   1696 
   1697   va_start (args, first_element);
   1698 #ifndef G_OS_WIN32
   1699   str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
   1700 #else
   1701   str = g_build_pathname_va (first_element, &args, NULL);
   1702 #endif
   1703   va_end (args);
   1704 
   1705   return str;
   1706 }
   1707 
   1708 #define KILOBYTE_FACTOR 1024.0
   1709 #define MEGABYTE_FACTOR (1024.0 * 1024.0)
   1710 #define GIGABYTE_FACTOR (1024.0 * 1024.0 * 1024.0)
   1711 
   1712 /**
   1713  * g_format_size_for_display:
   1714  * @size: a size in bytes.
   1715  *
   1716  * Formats a size (for example the size of a file) into a human readable string.
   1717  * Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed
   1718  * rounded to the nearest  tenth. E.g. the file size 3292528 bytes will be
   1719  * converted into the string "3.1 MB".
   1720  *
   1721  * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
   1722  *
   1723  * This string should be freed with g_free() when not needed any longer.
   1724  *
   1725  * Returns: a newly-allocated formatted string containing a human readable
   1726  *          file size.
   1727  *
   1728  * Since: 2.16
   1729  **/
   1730 char *
   1731 g_format_size_for_display (goffset size)
   1732 {
   1733   if (size < (goffset) KILOBYTE_FACTOR)
   1734     return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
   1735   else
   1736     {
   1737       gdouble displayed_size;
   1738 
   1739       if (size < (goffset) MEGABYTE_FACTOR)
   1740 	{
   1741 	  displayed_size = (gdouble) size / KILOBYTE_FACTOR;
   1742 	  return g_strdup_printf (_("%.1f KB"), displayed_size);
   1743 	}
   1744       else if (size < (goffset) GIGABYTE_FACTOR)
   1745 	{
   1746 	  displayed_size = (gdouble) size / MEGABYTE_FACTOR;
   1747 	  return g_strdup_printf (_("%.1f MB"), displayed_size);
   1748 	}
   1749       else
   1750 	{
   1751 	  displayed_size = (gdouble) size / GIGABYTE_FACTOR;
   1752 	  return g_strdup_printf (_("%.1f GB"), displayed_size);
   1753 	}
   1754     }
   1755 }
   1756 
   1757 
   1758 /**
   1759  * g_file_read_link:
   1760  * @filename: the symbolic link
   1761  * @error: return location for a #GError
   1762  *
   1763  * Reads the contents of the symbolic link @filename like the POSIX
   1764  * readlink() function.  The returned string is in the encoding used
   1765  * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
   1766  *
   1767  * Returns: A newly-allocated string with the contents of the symbolic link,
   1768  *          or %NULL if an error occurred.
   1769  *
   1770  * Since: 2.4
   1771  */
   1772 gchar *
   1773 g_file_read_link (const gchar  *filename,
   1774 	          GError      **error)
   1775 {
   1776 #ifdef HAVE_READLINK
   1777   gchar *buffer;
   1778   guint size;
   1779   gint read_size;
   1780 
   1781   size = 256;
   1782   buffer = g_malloc (size);
   1783 
   1784   while (TRUE)
   1785     {
   1786       read_size = readlink (filename, buffer, size);
   1787       if (read_size < 0) {
   1788 	int save_errno = errno;
   1789 	gchar *display_filename = g_filename_display_name (filename);
   1790 
   1791 	g_free (buffer);
   1792 	g_set_error (error,
   1793 		     G_FILE_ERROR,
   1794 		     g_file_error_from_errno (save_errno),
   1795 		     _("Failed to read the symbolic link '%s': %s"),
   1796 		     display_filename,
   1797 		     g_strerror (save_errno));
   1798 	g_free (display_filename);
   1799 
   1800 	return NULL;
   1801       }
   1802 
   1803       if (read_size < size)
   1804 	{
   1805 	  buffer[read_size] = 0;
   1806 	  return buffer;
   1807 	}
   1808 
   1809       size *= 2;
   1810       buffer = g_realloc (buffer, size);
   1811     }
   1812 #else
   1813   g_set_error_literal (error,
   1814                        G_FILE_ERROR,
   1815                        G_FILE_ERROR_INVAL,
   1816                        _("Symbolic links not supported"));
   1817 
   1818   return NULL;
   1819 #endif
   1820 }
   1821 
   1822 /* NOTE : Keep this part last to ensure nothing in this file uses the
   1823  * below binary compatibility versions.
   1824  */
   1825 #if defined (G_OS_WIN32) && !defined (_WIN64)
   1826 
   1827 /* Binary compatibility versions. Will be called by code compiled
   1828  * against quite old (pre-2.8, I think) headers only, not from more
   1829  * recently compiled code.
   1830  */
   1831 
   1832 #undef g_file_test
   1833 
   1834 gboolean
   1835 g_file_test (const gchar *filename,
   1836              GFileTest    test)
   1837 {
   1838   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
   1839   gboolean retval;
   1840 
   1841   if (utf8_filename == NULL)
   1842     return FALSE;
   1843 
   1844   retval = g_file_test_utf8 (utf8_filename, test);
   1845 
   1846   g_free (utf8_filename);
   1847 
   1848   return retval;
   1849 }
   1850 
   1851 #undef g_file_get_contents
   1852 
   1853 gboolean
   1854 g_file_get_contents (const gchar  *filename,
   1855                      gchar       **contents,
   1856                      gsize        *length,
   1857                      GError      **error)
   1858 {
   1859   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
   1860   gboolean retval;
   1861 
   1862   if (utf8_filename == NULL)
   1863     return FALSE;
   1864 
   1865   retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
   1866 
   1867   g_free (utf8_filename);
   1868 
   1869   return retval;
   1870 }
   1871 
   1872 #undef g_mkstemp
   1873 
   1874 gint
   1875 g_mkstemp (gchar *tmpl)
   1876 {
   1877   char *XXXXXX;
   1878   int count, fd;
   1879   static const char letters[] =
   1880     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
   1881   static const int NLETTERS = sizeof (letters) - 1;
   1882   glong value;
   1883   GTimeVal tv;
   1884   static int counter = 0;
   1885 
   1886   /* find the last occurrence of 'XXXXXX' */
   1887   XXXXXX = g_strrstr (tmpl, "XXXXXX");
   1888 
   1889   if (!XXXXXX)
   1890     {
   1891       errno = EINVAL;
   1892       return -1;
   1893     }
   1894 
   1895   /* Get some more or less random data.  */
   1896   g_get_current_time (&tv);
   1897   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
   1898 
   1899   for (count = 0; count < 100; value += 7777, ++count)
   1900     {
   1901       glong v = value;
   1902 
   1903       /* Fill in the random bits.  */
   1904       XXXXXX[0] = letters[v % NLETTERS];
   1905       v /= NLETTERS;
   1906       XXXXXX[1] = letters[v % NLETTERS];
   1907       v /= NLETTERS;
   1908       XXXXXX[2] = letters[v % NLETTERS];
   1909       v /= NLETTERS;
   1910       XXXXXX[3] = letters[v % NLETTERS];
   1911       v /= NLETTERS;
   1912       XXXXXX[4] = letters[v % NLETTERS];
   1913       v /= NLETTERS;
   1914       XXXXXX[5] = letters[v % NLETTERS];
   1915 
   1916       /* This is the backward compatibility system codepage version,
   1917        * thus use normal open().
   1918        */
   1919       fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
   1920 
   1921       if (fd >= 0)
   1922 	return fd;
   1923       else if (errno != EEXIST)
   1924 	/* Any other error will apply also to other names we might
   1925 	 *  try, and there are 2^32 or so of them, so give up now.
   1926 	 */
   1927 	return -1;
   1928     }
   1929 
   1930   /* We got out of the loop because we ran out of combinations to try.  */
   1931   errno = EEXIST;
   1932   return -1;
   1933 }
   1934 
   1935 #undef g_file_open_tmp
   1936 
   1937 gint
   1938 g_file_open_tmp (const gchar  *tmpl,
   1939 		 gchar       **name_used,
   1940 		 GError      **error)
   1941 {
   1942   gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
   1943   gchar *utf8_name_used;
   1944   gint retval;
   1945 
   1946   if (utf8_tmpl == NULL)
   1947     return -1;
   1948 
   1949   retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
   1950 
   1951   if (retval == -1)
   1952     return -1;
   1953 
   1954   if (name_used)
   1955     *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
   1956 
   1957   g_free (utf8_name_used);
   1958 
   1959   return retval;
   1960 }
   1961 
   1962 #endif
   1963 
   1964 #define __G_FILEUTILS_C__
   1965 #include "galiasdef.c"
   1966