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