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