Merge remote-tracking branch 'gvdb/master'
[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)
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: name of a file to read contents from, in the GLib file name encoding
809  * @contents: location to store an allocated string, use g_free() to free
810  *     the returned string
811  * @length: 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       g_unlink (tmp_name);
967       
968       goto out;
969     }
970
971 #ifdef BTRFS_SUPER_MAGIC
972   {
973     struct statfs buf;
974
975     /* On Linux, on btrfs, skip the fsync since rename-over-existing is
976      * guaranteed to be atomic and this is the only case in which we
977      * would fsync() anyway.
978      */
979
980     if (fstatfs (fd, &buf) == 0 && buf.f_type == BTRFS_SUPER_MAGIC)
981       goto no_fsync;
982   }
983 #endif
984   
985 #ifdef HAVE_FSYNC
986   {
987     struct stat statbuf;
988
989     errno = 0;
990     /* If the final destination exists and is > 0 bytes, we want to sync the
991      * newly written file to ensure the data is on disk when we rename over
992      * the destination. Otherwise if we get a system crash we can lose both
993      * the new and the old file on some filesystems. (I.E. those that don't
994      * guarantee the data is written to the disk before the metadata.)
995      */
996     if (g_lstat (dest_file, &statbuf) == 0 &&
997         statbuf.st_size > 0 &&
998         fsync (fileno (file)) != 0)
999       {
1000         save_errno = errno;
1001
1002         g_set_error (err,
1003                      G_FILE_ERROR,
1004                      g_file_error_from_errno (save_errno),
1005                      _("Failed to write file '%s': fsync() failed: %s"),
1006                      display_name,
1007                      g_strerror (save_errno));
1008
1009         g_unlink (tmp_name);
1010
1011         goto out;
1012       }
1013   }
1014 #endif
1015  no_fsync:
1016   
1017   errno = 0;
1018   if (fclose (file) == EOF)
1019     { 
1020       save_errno = errno;
1021       
1022       g_set_error (err,
1023                    G_FILE_ERROR,
1024                    g_file_error_from_errno (save_errno),
1025                    _("Failed to close file '%s': fclose() failed: %s"),
1026                    display_name, 
1027                    g_strerror (save_errno));
1028
1029       g_unlink (tmp_name);
1030       
1031       goto out;
1032     }
1033
1034   retval = g_strdup (tmp_name);
1035   
1036  out:
1037   g_free (tmp_name);
1038   g_free (display_name);
1039   
1040   return retval;
1041 }
1042
1043 /**
1044  * g_file_set_contents:
1045  * @filename: name of a file to write @contents to, in the GLib file name
1046  *   encoding
1047  * @contents: string to write to the file
1048  * @length: length of @contents, or -1 if @contents is a nul-terminated string
1049  * @error: return location for a #GError, or %NULL
1050  *
1051  * Writes all of @contents to a file named @filename, with good error checking.
1052  * If a file called @filename already exists it will be overwritten.
1053  *
1054  * This write is atomic in the sense that it is first written to a temporary
1055  * file which is then renamed to the final name. Notes:
1056  * <itemizedlist>
1057  * <listitem>
1058  *    On Unix, if @filename already exists hard links to @filename will break.
1059  *    Also since the file is recreated, existing permissions, access control
1060  *    lists, metadata etc. may be lost. If @filename is a symbolic link,
1061  *    the link itself will be replaced, not the linked file.
1062  * </listitem>
1063  * <listitem>
1064  *   On Windows renaming a file will not remove an existing file with the
1065  *   new name, so on Windows there is a race condition between the existing
1066  *   file being removed and the temporary file being renamed.
1067  * </listitem>
1068  * <listitem>
1069  *   On Windows there is no way to remove a file that is open to some
1070  *   process, or mapped into memory. Thus, this function will fail if
1071  *   @filename already exists and is open.
1072  * </listitem>
1073  * </itemizedlist>
1074  *
1075  * If the call was sucessful, it returns %TRUE. If the call was not successful,
1076  * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1077  * Possible error codes are those in the #GFileError enumeration.
1078  *
1079  * Note that the name for the temporary file is constructed by appending up
1080  * to 7 characters to @filename.
1081  *
1082  * Return value: %TRUE on success, %FALSE if an error occurred
1083  *
1084  * Since: 2.8
1085  **/
1086 gboolean
1087 g_file_set_contents (const gchar  *filename,
1088                      const gchar  *contents,
1089                      gssize        length,
1090                      GError      **error)
1091 {
1092   gchar *tmp_filename;
1093   gboolean retval;
1094   GError *rename_error = NULL;
1095   
1096   g_return_val_if_fail (filename != NULL, FALSE);
1097   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1098   g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1099   g_return_val_if_fail (length >= -1, FALSE);
1100   
1101   if (length == -1)
1102     length = strlen (contents);
1103
1104   tmp_filename = write_to_temp_file (contents, length, filename, error);
1105   
1106   if (!tmp_filename)
1107     {
1108       retval = FALSE;
1109       goto out;
1110     }
1111
1112   if (!rename_file (tmp_filename, filename, &rename_error))
1113     {
1114 #ifndef G_OS_WIN32
1115
1116       g_unlink (tmp_filename);
1117       g_propagate_error (error, rename_error);
1118       retval = FALSE;
1119       goto out;
1120
1121 #else /* G_OS_WIN32 */
1122       
1123       /* Renaming failed, but on Windows this may just mean
1124        * the file already exists. So if the target file
1125        * exists, try deleting it and do the rename again.
1126        */
1127       if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1128         {
1129           g_unlink (tmp_filename);
1130           g_propagate_error (error, rename_error);
1131           retval = FALSE;
1132           goto out;
1133         }
1134
1135       g_error_free (rename_error);
1136       
1137       if (g_unlink (filename) == -1)
1138         {
1139           gchar *display_filename = g_filename_display_name (filename);
1140
1141           int save_errno = errno;
1142           
1143           g_set_error (error,
1144                        G_FILE_ERROR,
1145                        g_file_error_from_errno (save_errno),
1146                        _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1147                        display_filename,
1148                        g_strerror (save_errno));
1149
1150           g_free (display_filename);
1151           g_unlink (tmp_filename);
1152           retval = FALSE;
1153           goto out;
1154         }
1155       
1156       if (!rename_file (tmp_filename, filename, error))
1157         {
1158           g_unlink (tmp_filename);
1159           retval = FALSE;
1160           goto out;
1161         }
1162
1163 #endif
1164     }
1165
1166   retval = TRUE;
1167   
1168  out:
1169   g_free (tmp_filename);
1170   return retval;
1171 }
1172
1173 /**
1174  * g_mkstemp_full:
1175  * @tmpl: template filename
1176  * @flags: flags to pass to an open() call in addition to O_EXCL and
1177  *         O_CREAT, which are passed automatically
1178  * @mode: permissios to create the temporary file with
1179  *
1180  * Opens a temporary file. See the mkstemp() documentation
1181  * on most UNIX-like systems.
1182  *
1183  * The parameter is a string that should follow the rules for
1184  * mkstemp() templates, i.e. contain the string "XXXXXX".
1185  * g_mkstemp_full() is slightly more flexible than mkstemp()
1186  * in that the sequence does not have to occur at the very end of the
1187  * template and you can pass a @mode and additional @flags. The X
1188  * string will be modified to form the name of a file that didn't exist.
1189  * The string should be in the GLib file name encoding. Most importantly,
1190  * on Windows it should be in UTF-8.
1191  *
1192  * Return value: A file handle (as from open()) to the file
1193  *     opened for reading and writing. The file handle should be
1194  *     closed with close(). In case of errors, -1 is returned.
1195  *
1196  * Since: 2.22
1197  */
1198 /*
1199  * g_mkstemp_full based on the mkstemp implementation from the GNU C library.
1200  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1201  */
1202 gint
1203 g_mkstemp_full (gchar *tmpl, 
1204                 int    flags,
1205                 int    mode)
1206 {
1207   char *XXXXXX;
1208   int count, fd;
1209   static const char letters[] =
1210     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1211   static const int NLETTERS = sizeof (letters) - 1;
1212   glong value;
1213   GTimeVal tv;
1214   static int counter = 0;
1215
1216   g_return_val_if_fail (tmpl != NULL, -1);
1217
1218
1219   /* find the last occurrence of "XXXXXX" */
1220   XXXXXX = g_strrstr (tmpl, "XXXXXX");
1221
1222   if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1223     {
1224       errno = EINVAL;
1225       return -1;
1226     }
1227
1228   /* Get some more or less random data.  */
1229   g_get_current_time (&tv);
1230   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1231
1232   for (count = 0; count < 100; value += 7777, ++count)
1233     {
1234       glong v = value;
1235
1236       /* Fill in the random bits.  */
1237       XXXXXX[0] = letters[v % NLETTERS];
1238       v /= NLETTERS;
1239       XXXXXX[1] = letters[v % NLETTERS];
1240       v /= NLETTERS;
1241       XXXXXX[2] = letters[v % NLETTERS];
1242       v /= NLETTERS;
1243       XXXXXX[3] = letters[v % NLETTERS];
1244       v /= NLETTERS;
1245       XXXXXX[4] = letters[v % NLETTERS];
1246       v /= NLETTERS;
1247       XXXXXX[5] = letters[v % NLETTERS];
1248
1249       /* tmpl is in UTF-8 on Windows, thus use g_open() */
1250       fd = g_open (tmpl, flags | O_CREAT | O_EXCL, mode);
1251
1252       if (fd >= 0)
1253         return fd;
1254       else if (errno != EEXIST)
1255         /* Any other error will apply also to other names we might
1256          *  try, and there are 2^32 or so of them, so give up now.
1257          */
1258         return -1;
1259     }
1260
1261   /* We got out of the loop because we ran out of combinations to try.  */
1262   errno = EEXIST;
1263   return -1;
1264 }
1265
1266 /**
1267  * g_mkstemp:
1268  * @tmpl: template filename
1269  *
1270  * Opens a temporary file. See the mkstemp() documentation
1271  * on most UNIX-like systems. 
1272  *
1273  * The parameter is a string that should follow the rules for
1274  * mkstemp() templates, i.e. contain the string "XXXXXX". 
1275  * g_mkstemp() is slightly more flexible than mkstemp()
1276  * in that the sequence does not have to occur at the very end of the 
1277  * template. The X string will 
1278  * be modified to form the name of a file that didn't exist.
1279  * The string should be in the GLib file name encoding. Most importantly, 
1280  * on Windows it should be in UTF-8.
1281  *
1282  * Return value: A file handle (as from open()) to the file
1283  * opened for reading and writing. The file is opened in binary mode
1284  * on platforms where there is a difference. The file handle should be
1285  * closed with close(). In case of errors, -1 is returned.  
1286  */ 
1287 gint
1288 g_mkstemp (gchar *tmpl)
1289 {
1290   return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1291 }
1292
1293 /**
1294  * g_file_open_tmp:
1295  * @tmpl: Template for file name, as in g_mkstemp(), basename only,
1296  *        or %NULL, to a default template
1297  * @name_used: location to store actual name used, or %NULL
1298  * @error: return location for a #GError
1299  *
1300  * Opens a file for writing in the preferred directory for temporary
1301  * files (as returned by g_get_tmp_dir()). 
1302  *
1303  * @tmpl should be a string in the GLib file name encoding containing 
1304  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1305  * However, unlike these functions, the template should only be a
1306  * basename, no directory components are allowed. If template is
1307  * %NULL, a default template is used.
1308  *
1309  * Note that in contrast to g_mkstemp() (and mkstemp()) 
1310  * @tmpl is not modified, and might thus be a read-only literal string.
1311  *
1312  * The actual name used is returned in @name_used if non-%NULL. This
1313  * string should be freed with g_free() when not needed any longer.
1314  * The returned name is in the GLib file name encoding.
1315  *
1316  * Return value: A file handle (as from open()) to 
1317  * the file opened for reading and writing. The file is opened in binary 
1318  * mode on platforms where there is a difference. The file handle should be
1319  * closed with close(). In case of errors, -1 is returned 
1320  * and @error will be set.
1321  **/
1322 gint
1323 g_file_open_tmp (const gchar  *tmpl,
1324                  gchar       **name_used,
1325                  GError      **error)
1326 {
1327   int retval;
1328   const char *tmpdir;
1329   const char *sep;
1330   char *fulltemplate;
1331   const char *slash;
1332
1333   if (tmpl == NULL)
1334     tmpl = ".XXXXXX";
1335
1336   if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1337 #ifdef G_OS_WIN32
1338       || (strchr (tmpl, '/') != NULL && (slash = "/"))
1339 #endif
1340       )
1341     {
1342       gchar *display_tmpl = g_filename_display_name (tmpl);
1343       char c[2];
1344       c[0] = *slash;
1345       c[1] = '\0';
1346
1347       g_set_error (error,
1348                    G_FILE_ERROR,
1349                    G_FILE_ERROR_FAILED,
1350                    _("Template '%s' invalid, should not contain a '%s'"),
1351                    display_tmpl, c);
1352       g_free (display_tmpl);
1353
1354       return -1;
1355     }
1356   
1357   if (strstr (tmpl, "XXXXXX") == NULL)
1358     {
1359       gchar *display_tmpl = g_filename_display_name (tmpl);
1360       g_set_error (error,
1361                    G_FILE_ERROR,
1362                    G_FILE_ERROR_FAILED,
1363                    _("Template '%s' doesn't contain XXXXXX"),
1364                    display_tmpl);
1365       g_free (display_tmpl);
1366       return -1;
1367     }
1368
1369   tmpdir = g_get_tmp_dir ();
1370
1371   if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1372     sep = "";
1373   else
1374     sep = G_DIR_SEPARATOR_S;
1375
1376   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1377
1378   retval = g_mkstemp (fulltemplate);
1379
1380   if (retval == -1)
1381     {
1382       int save_errno = errno;
1383       gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1384
1385       g_set_error (error,
1386                    G_FILE_ERROR,
1387                    g_file_error_from_errno (save_errno),
1388                    _("Failed to create file '%s': %s"),
1389                    display_fulltemplate, g_strerror (save_errno));
1390       g_free (display_fulltemplate);
1391       g_free (fulltemplate);
1392       return -1;
1393     }
1394
1395   if (name_used)
1396     *name_used = fulltemplate;
1397   else
1398     g_free (fulltemplate);
1399
1400   return retval;
1401 }
1402
1403 static gchar *
1404 g_build_path_va (const gchar  *separator,
1405                  const gchar  *first_element,
1406                  va_list      *args,
1407                  gchar       **str_array)
1408 {
1409   GString *result;
1410   gint separator_len = strlen (separator);
1411   gboolean is_first = TRUE;
1412   gboolean have_leading = FALSE;
1413   const gchar *single_element = NULL;
1414   const gchar *next_element;
1415   const gchar *last_trailing = NULL;
1416   gint i = 0;
1417
1418   result = g_string_new (NULL);
1419
1420   if (str_array)
1421     next_element = str_array[i++];
1422   else
1423     next_element = first_element;
1424
1425   while (TRUE)
1426     {
1427       const gchar *element;
1428       const gchar *start;
1429       const gchar *end;
1430
1431       if (next_element)
1432         {
1433           element = next_element;
1434           if (str_array)
1435             next_element = str_array[i++];
1436           else
1437             next_element = va_arg (*args, gchar *);
1438         }
1439       else
1440         break;
1441
1442       /* Ignore empty elements */
1443       if (!*element)
1444         continue;
1445       
1446       start = element;
1447
1448       if (separator_len)
1449         {
1450           while (strncmp (start, separator, separator_len) == 0)
1451             start += separator_len;
1452         }
1453
1454       end = start + strlen (start);
1455       
1456       if (separator_len)
1457         {
1458           while (end >= start + separator_len &&
1459                  strncmp (end - separator_len, separator, separator_len) == 0)
1460             end -= separator_len;
1461           
1462           last_trailing = end;
1463           while (last_trailing >= element + separator_len &&
1464                  strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1465             last_trailing -= separator_len;
1466
1467           if (!have_leading)
1468             {
1469               /* If the leading and trailing separator strings are in the
1470                * same element and overlap, the result is exactly that element
1471                */
1472               if (last_trailing <= start)
1473                 single_element = element;
1474                   
1475               g_string_append_len (result, element, start - element);
1476               have_leading = TRUE;
1477             }
1478           else
1479             single_element = NULL;
1480         }
1481
1482       if (end == start)
1483         continue;
1484
1485       if (!is_first)
1486         g_string_append (result, separator);
1487       
1488       g_string_append_len (result, start, end - start);
1489       is_first = FALSE;
1490     }
1491
1492   if (single_element)
1493     {
1494       g_string_free (result, TRUE);
1495       return g_strdup (single_element);
1496     }
1497   else
1498     {
1499       if (last_trailing)
1500         g_string_append (result, last_trailing);
1501   
1502       return g_string_free (result, FALSE);
1503     }
1504 }
1505
1506 /**
1507  * g_build_pathv:
1508  * @separator: a string used to separator the elements of the path.
1509  * @args: %NULL-terminated array of strings containing the path elements.
1510  * 
1511  * Behaves exactly like g_build_path(), but takes the path elements 
1512  * as a string array, instead of varargs. This function is mainly
1513  * meant for language bindings.
1514  *
1515  * Return value: a newly-allocated string that must be freed with g_free().
1516  *
1517  * Since: 2.8
1518  */
1519 gchar *
1520 g_build_pathv (const gchar  *separator,
1521                gchar       **args)
1522 {
1523   if (!args)
1524     return NULL;
1525
1526   return g_build_path_va (separator, NULL, NULL, args);
1527 }
1528
1529
1530 /**
1531  * g_build_path:
1532  * @separator: a string used to separator the elements of the path.
1533  * @first_element: the first element in the path
1534  * @Varargs: remaining elements in path, terminated by %NULL
1535  * 
1536  * Creates a path from a series of elements using @separator as the
1537  * separator between elements. At the boundary between two elements,
1538  * any trailing occurrences of separator in the first element, or
1539  * leading occurrences of separator in the second element are removed
1540  * and exactly one copy of the separator is inserted.
1541  *
1542  * Empty elements are ignored.
1543  *
1544  * The number of leading copies of the separator on the result is
1545  * the same as the number of leading copies of the separator on
1546  * the first non-empty element.
1547  *
1548  * The number of trailing copies of the separator on the result is
1549  * the same as the number of trailing copies of the separator on
1550  * the last non-empty element. (Determination of the number of
1551  * trailing copies is done without stripping leading copies, so
1552  * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1553  * has 1 trailing copy.)
1554  *
1555  * However, if there is only a single non-empty element, and there
1556  * are no characters in that element not part of the leading or
1557  * trailing separators, then the result is exactly the original value
1558  * of that element.
1559  *
1560  * Other than for determination of the number of leading and trailing
1561  * copies of the separator, elements consisting only of copies
1562  * of the separator are ignored.
1563  * 
1564  * Return value: a newly-allocated string that must be freed with g_free().
1565  **/
1566 gchar *
1567 g_build_path (const gchar *separator,
1568               const gchar *first_element,
1569               ...)
1570 {
1571   gchar *str;
1572   va_list args;
1573
1574   g_return_val_if_fail (separator != NULL, NULL);
1575
1576   va_start (args, first_element);
1577   str = g_build_path_va (separator, first_element, &args, NULL);
1578   va_end (args);
1579
1580   return str;
1581 }
1582
1583 #ifdef G_OS_WIN32
1584
1585 static gchar *
1586 g_build_pathname_va (const gchar  *first_element,
1587                      va_list      *args,
1588                      gchar       **str_array)
1589 {
1590   /* Code copied from g_build_pathv(), and modified to use two
1591    * alternative single-character separators.
1592    */
1593   GString *result;
1594   gboolean is_first = TRUE;
1595   gboolean have_leading = FALSE;
1596   const gchar *single_element = NULL;
1597   const gchar *next_element;
1598   const gchar *last_trailing = NULL;
1599   gchar current_separator = '\\';
1600   gint i = 0;
1601
1602   result = g_string_new (NULL);
1603
1604   if (str_array)
1605     next_element = str_array[i++];
1606   else
1607     next_element = first_element;
1608   
1609   while (TRUE)
1610     {
1611       const gchar *element;
1612       const gchar *start;
1613       const gchar *end;
1614
1615       if (next_element)
1616         {
1617           element = next_element;
1618           if (str_array)
1619             next_element = str_array[i++];
1620           else
1621             next_element = va_arg (*args, gchar *);
1622         }
1623       else
1624         break;
1625
1626       /* Ignore empty elements */
1627       if (!*element)
1628         continue;
1629       
1630       start = element;
1631
1632       if (TRUE)
1633         {
1634           while (start &&
1635                  (*start == '\\' || *start == '/'))
1636             {
1637               current_separator = *start;
1638               start++;
1639             }
1640         }
1641
1642       end = start + strlen (start);
1643       
1644       if (TRUE)
1645         {
1646           while (end >= start + 1 &&
1647                  (end[-1] == '\\' || end[-1] == '/'))
1648             {
1649               current_separator = end[-1];
1650               end--;
1651             }
1652           
1653           last_trailing = end;
1654           while (last_trailing >= element + 1 &&
1655                  (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1656             last_trailing--;
1657
1658           if (!have_leading)
1659             {
1660               /* If the leading and trailing separator strings are in the
1661                * same element and overlap, the result is exactly that element
1662                */
1663               if (last_trailing <= start)
1664                 single_element = element;
1665                   
1666               g_string_append_len (result, element, start - element);
1667               have_leading = TRUE;
1668             }
1669           else
1670             single_element = NULL;
1671         }
1672
1673       if (end == start)
1674         continue;
1675
1676       if (!is_first)
1677         g_string_append_len (result, &current_separator, 1);
1678       
1679       g_string_append_len (result, start, end - start);
1680       is_first = FALSE;
1681     }
1682
1683   if (single_element)
1684     {
1685       g_string_free (result, TRUE);
1686       return g_strdup (single_element);
1687     }
1688   else
1689     {
1690       if (last_trailing)
1691         g_string_append (result, last_trailing);
1692   
1693       return g_string_free (result, FALSE);
1694     }
1695 }
1696
1697 #endif
1698
1699 /**
1700  * g_build_filenamev:
1701  * @args: %NULL-terminated array of strings containing the path elements.
1702  * 
1703  * Behaves exactly like g_build_filename(), but takes the path elements 
1704  * as a string array, instead of varargs. This function is mainly
1705  * meant for language bindings.
1706  *
1707  * Return value: a newly-allocated string that must be freed with g_free().
1708  * 
1709  * Since: 2.8
1710  */
1711 gchar *
1712 g_build_filenamev (gchar **args)
1713 {
1714   gchar *str;
1715
1716 #ifndef G_OS_WIN32
1717   str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1718 #else
1719   str = g_build_pathname_va (NULL, NULL, args);
1720 #endif
1721
1722   return str;
1723 }
1724
1725 /**
1726  * g_build_filename:
1727  * @first_element: the first element in the path
1728  * @Varargs: remaining elements in path, terminated by %NULL
1729  * 
1730  * Creates a filename from a series of elements using the correct
1731  * separator for filenames.
1732  *
1733  * On Unix, this function behaves identically to <literal>g_build_path
1734  * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1735  *
1736  * On Windows, it takes into account that either the backslash
1737  * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1738  * as separator in filenames, but otherwise behaves as on Unix. When
1739  * file pathname separators need to be inserted, the one that last
1740  * previously occurred in the parameters (reading from left to right)
1741  * is used.
1742  *
1743  * No attempt is made to force the resulting filename to be an absolute
1744  * path. If the first element is a relative path, the result will
1745  * be a relative path. 
1746  * 
1747  * Return value: a newly-allocated string that must be freed with g_free().
1748  **/
1749 gchar *
1750 g_build_filename (const gchar *first_element, 
1751                   ...)
1752 {
1753   gchar *str;
1754   va_list args;
1755
1756   va_start (args, first_element);
1757 #ifndef G_OS_WIN32
1758   str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1759 #else
1760   str = g_build_pathname_va (first_element, &args, NULL);
1761 #endif
1762   va_end (args);
1763
1764   return str;
1765 }
1766
1767 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
1768 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
1769 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
1770 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
1771 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
1772 #define EXABYTE_FACTOR  (PETABYTE_FACTOR * KILOBYTE_FACTOR)
1773
1774 /**
1775  * g_format_size_for_display:
1776  * @size: a size in bytes.
1777  * 
1778  * Formats a size (for example the size of a file) into a human readable string.
1779  * Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed 
1780  * rounded to the nearest  tenth. E.g. the file size 3292528 bytes will be
1781  * converted into the string "3.1 MB".
1782  *
1783  * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
1784  *
1785  * This string should be freed with g_free() when not needed any longer.
1786  *
1787  * Returns: a newly-allocated formatted string containing a human readable
1788  *          file size.
1789  *
1790  * Since: 2.16
1791  **/
1792 char *
1793 g_format_size_for_display (goffset size)
1794 {
1795   if (size < (goffset) KILOBYTE_FACTOR)
1796     return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
1797   else
1798     {
1799       gdouble displayed_size;
1800       
1801       if (size < (goffset) MEGABYTE_FACTOR)
1802         {
1803           displayed_size = (gdouble) size / (gdouble) KILOBYTE_FACTOR;
1804           return g_strdup_printf (_("%.1f KB"), displayed_size);
1805         }
1806       else if (size < (goffset) GIGABYTE_FACTOR)
1807         {
1808           displayed_size = (gdouble) size / (gdouble) MEGABYTE_FACTOR;
1809           return g_strdup_printf (_("%.1f MB"), displayed_size);
1810         }
1811       else if (size < (goffset) TERABYTE_FACTOR)
1812         {
1813           displayed_size = (gdouble) size / (gdouble) GIGABYTE_FACTOR;
1814           return g_strdup_printf (_("%.1f GB"), displayed_size);
1815         }
1816       else if (size < (goffset) PETABYTE_FACTOR)
1817         {
1818           displayed_size = (gdouble) size / (gdouble) TERABYTE_FACTOR;
1819           return g_strdup_printf (_("%.1f TB"), displayed_size);
1820         }
1821       else if (size < (goffset) EXABYTE_FACTOR)
1822         {
1823           displayed_size = (gdouble) size / (gdouble) PETABYTE_FACTOR;
1824           return g_strdup_printf (_("%.1f PB"), displayed_size);
1825         }
1826       else
1827         {
1828           displayed_size = (gdouble) size / (gdouble) EXABYTE_FACTOR;
1829           return g_strdup_printf (_("%.1f EB"), displayed_size);
1830         }
1831     }
1832 }
1833
1834
1835 /**
1836  * g_file_read_link:
1837  * @filename: the symbolic link
1838  * @error: return location for a #GError
1839  *
1840  * Reads the contents of the symbolic link @filename like the POSIX
1841  * readlink() function.  The returned string is in the encoding used
1842  * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1843  *
1844  * Returns: A newly-allocated string with the contents of the symbolic link, 
1845  *          or %NULL if an error occurred.
1846  *
1847  * Since: 2.4
1848  */
1849 gchar *
1850 g_file_read_link (const gchar  *filename,
1851                   GError      **error)
1852 {
1853 #ifdef HAVE_READLINK
1854   gchar *buffer;
1855   guint size;
1856   gint read_size;    
1857   
1858   size = 256; 
1859   buffer = g_malloc (size);
1860   
1861   while (TRUE) 
1862     {
1863       read_size = readlink (filename, buffer, size);
1864       if (read_size < 0) {
1865         int save_errno = errno;
1866         gchar *display_filename = g_filename_display_name (filename);
1867
1868         g_free (buffer);
1869         g_set_error (error,
1870                      G_FILE_ERROR,
1871                      g_file_error_from_errno (save_errno),
1872                      _("Failed to read the symbolic link '%s': %s"),
1873                      display_filename, 
1874                      g_strerror (save_errno));
1875         g_free (display_filename);
1876         
1877         return NULL;
1878       }
1879     
1880       if (read_size < size) 
1881         {
1882           buffer[read_size] = 0;
1883           return buffer;
1884         }
1885       
1886       size *= 2;
1887       buffer = g_realloc (buffer, size);
1888     }
1889 #else
1890   g_set_error_literal (error,
1891                        G_FILE_ERROR,
1892                        G_FILE_ERROR_INVAL,
1893                        _("Symbolic links not supported"));
1894         
1895   return NULL;
1896 #endif
1897 }
1898
1899 /* NOTE : Keep this part last to ensure nothing in this file uses the
1900  * below binary compatibility versions.
1901  */
1902 #if defined (G_OS_WIN32) && !defined (_WIN64)
1903
1904 /* Binary compatibility versions. Will be called by code compiled
1905  * against quite old (pre-2.8, I think) headers only, not from more
1906  * recently compiled code.
1907  */
1908
1909 #undef g_file_test
1910
1911 gboolean
1912 g_file_test (const gchar *filename,
1913              GFileTest    test)
1914 {
1915   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
1916   gboolean retval;
1917
1918   if (utf8_filename == NULL)
1919     return FALSE;
1920
1921   retval = g_file_test_utf8 (utf8_filename, test);
1922
1923   g_free (utf8_filename);
1924
1925   return retval;
1926 }
1927
1928 #undef g_file_get_contents
1929
1930 gboolean
1931 g_file_get_contents (const gchar  *filename,
1932                      gchar       **contents,
1933                      gsize        *length,
1934                      GError      **error)
1935 {
1936   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
1937   gboolean retval;
1938
1939   if (utf8_filename == NULL)
1940     return FALSE;
1941
1942   retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
1943
1944   g_free (utf8_filename);
1945
1946   return retval;
1947 }
1948
1949 #undef g_mkstemp
1950
1951 gint
1952 g_mkstemp (gchar *tmpl)
1953 {
1954   char *XXXXXX;
1955   int count, fd;
1956   static const char letters[] =
1957     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1958   static const int NLETTERS = sizeof (letters) - 1;
1959   glong value;
1960   GTimeVal tv;
1961   static int counter = 0;
1962
1963   /* find the last occurrence of 'XXXXXX' */
1964   XXXXXX = g_strrstr (tmpl, "XXXXXX");
1965
1966   if (!XXXXXX)
1967     {
1968       errno = EINVAL;
1969       return -1;
1970     }
1971
1972   /* Get some more or less random data.  */
1973   g_get_current_time (&tv);
1974   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1975
1976   for (count = 0; count < 100; value += 7777, ++count)
1977     {
1978       glong v = value;
1979
1980       /* Fill in the random bits.  */
1981       XXXXXX[0] = letters[v % NLETTERS];
1982       v /= NLETTERS;
1983       XXXXXX[1] = letters[v % NLETTERS];
1984       v /= NLETTERS;
1985       XXXXXX[2] = letters[v % NLETTERS];
1986       v /= NLETTERS;
1987       XXXXXX[3] = letters[v % NLETTERS];
1988       v /= NLETTERS;
1989       XXXXXX[4] = letters[v % NLETTERS];
1990       v /= NLETTERS;
1991       XXXXXX[5] = letters[v % NLETTERS];
1992
1993       /* This is the backward compatibility system codepage version,
1994        * thus use normal open().
1995        */
1996       fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1997
1998       if (fd >= 0)
1999         return fd;
2000       else if (errno != EEXIST)
2001         /* Any other error will apply also to other names we might
2002          *  try, and there are 2^32 or so of them, so give up now.
2003          */
2004         return -1;
2005     }
2006
2007   /* We got out of the loop because we ran out of combinations to try.  */
2008   errno = EEXIST;
2009   return -1;
2010 }
2011
2012 #undef g_file_open_tmp
2013
2014 gint
2015 g_file_open_tmp (const gchar  *tmpl,
2016                  gchar       **name_used,
2017                  GError      **error)
2018 {
2019   gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
2020   gchar *utf8_name_used;
2021   gint retval;
2022
2023   if (utf8_tmpl == NULL)
2024     return -1;
2025
2026   retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
2027   
2028   if (retval == -1)
2029     return -1;
2030
2031   if (name_used)
2032     *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
2033
2034   g_free (utf8_name_used);
2035
2036   return retval;
2037 }
2038
2039 #endif