Add g_key_file_load_from_dirs for looking through a search path for a
[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 is safe to write to a file without being
156  * tricked into writing into a different location. It doesn't work!
157  *
158  * <informalexample><programlisting>
159  * /&ast; DON'T DO THIS &ast;/
160  *  if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) {
161  *    fd = g_open (filename, O_WRONLY);
162  *    /&ast; write to fd &ast;/
163  *  }
164  * </programlisting></informalexample>
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 #ifdef G_OS_WIN32
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       total_bytes += bytes;
581     }
582
583   fclose (f);
584
585   if (total_allocated == 0)
586     str = g_new (gchar, 1);
587
588   str[total_bytes] = '\0';
589
590   if (length)
591     *length = total_bytes;
592
593   *contents = str;
594
595   return TRUE;
596
597  error:
598
599   g_free (str);
600   fclose (f);
601
602   return FALSE;
603 }
604
605 #ifndef G_OS_WIN32
606
607 static gboolean
608 get_contents_regfile (const gchar *display_filename,
609                       struct stat *stat_buf,
610                       gint         fd,
611                       gchar      **contents,
612                       gsize       *length,
613                       GError     **error)
614 {
615   gchar *buf;
616   gsize bytes_read;
617   gsize size;
618   gsize alloc_size;
619   
620   size = stat_buf->st_size;
621
622   alloc_size = size + 1;
623   buf = g_try_malloc (alloc_size);
624
625   if (buf == NULL)
626     {
627       g_set_error (error,
628                    G_FILE_ERROR,
629                    G_FILE_ERROR_NOMEM,
630                    _("Could not allocate %lu bytes to read file \"%s\""),
631                    (gulong) alloc_size, 
632                    display_filename);
633
634       goto error;
635     }
636   
637   bytes_read = 0;
638   while (bytes_read < size)
639     {
640       gssize rc;
641           
642       rc = read (fd, buf + bytes_read, size - bytes_read);
643
644       if (rc < 0)
645         {
646           if (errno != EINTR) 
647             {
648               int save_errno = errno;
649
650               g_free (buf);
651               g_set_error (error,
652                            G_FILE_ERROR,
653                            g_file_error_from_errno (save_errno),
654                            _("Failed to read from file '%s': %s"),
655                            display_filename, 
656                            g_strerror (save_errno));
657
658               goto error;
659             }
660         }
661       else if (rc == 0)
662         break;
663       else
664         bytes_read += rc;
665     }
666       
667   buf[bytes_read] = '\0';
668
669   if (length)
670     *length = bytes_read;
671   
672   *contents = buf;
673
674   close (fd);
675
676   return TRUE;
677
678  error:
679
680   close (fd);
681   
682   return FALSE;
683 }
684
685 static gboolean
686 get_contents_posix (const gchar *filename,
687                     gchar      **contents,
688                     gsize       *length,
689                     GError     **error)
690 {
691   struct stat stat_buf;
692   gint fd;
693   gchar *display_filename = g_filename_display_name (filename);
694
695   /* O_BINARY useful on Cygwin */
696   fd = open (filename, O_RDONLY|O_BINARY);
697
698   if (fd < 0)
699     {
700       int save_errno = errno;
701
702       g_set_error (error,
703                    G_FILE_ERROR,
704                    g_file_error_from_errno (save_errno),
705                    _("Failed to open file '%s': %s"),
706                    display_filename, 
707                    g_strerror (save_errno));
708       g_free (display_filename);
709
710       return FALSE;
711     }
712
713   /* I don't think this will ever fail, aside from ENOMEM, but. */
714   if (fstat (fd, &stat_buf) < 0)
715     {
716       int save_errno = errno;
717
718       close (fd);
719       g_set_error (error,
720                    G_FILE_ERROR,
721                    g_file_error_from_errno (save_errno),
722                    _("Failed to get attributes of file '%s': fstat() failed: %s"),
723                    display_filename, 
724                    g_strerror (save_errno));
725       g_free (display_filename);
726
727       return FALSE;
728     }
729
730   if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
731     {
732       gboolean retval = get_contents_regfile (display_filename,
733                                               &stat_buf,
734                                               fd,
735                                               contents,
736                                               length,
737                                               error);
738       g_free (display_filename);
739
740       return retval;
741     }
742   else
743     {
744       FILE *f;
745       gboolean retval;
746
747       f = fdopen (fd, "r");
748       
749       if (f == NULL)
750         {
751           int save_errno = errno;
752
753           g_set_error (error,
754                        G_FILE_ERROR,
755                        g_file_error_from_errno (save_errno),
756                        _("Failed to open file '%s': fdopen() failed: %s"),
757                        display_filename, 
758                        g_strerror (save_errno));
759           g_free (display_filename);
760
761           return FALSE;
762         }
763   
764       retval = get_contents_stdio (display_filename, f, contents, length, error);
765       g_free (display_filename);
766
767       return retval;
768     }
769 }
770
771 #else  /* G_OS_WIN32 */
772
773 static gboolean
774 get_contents_win32 (const gchar *filename,
775                     gchar      **contents,
776                     gsize       *length,
777                     GError     **error)
778 {
779   FILE *f;
780   gboolean retval;
781   gchar *display_filename = g_filename_display_name (filename);
782   int save_errno;
783   
784   f = g_fopen (filename, "rb");
785   save_errno = errno;
786
787   if (f == NULL)
788     {
789       g_set_error (error,
790                    G_FILE_ERROR,
791                    g_file_error_from_errno (save_errno),
792                    _("Failed to open file '%s': %s"),
793                    display_filename,
794                    g_strerror (save_errno));
795       g_free (display_filename);
796
797       return FALSE;
798     }
799   
800   retval = get_contents_stdio (display_filename, f, contents, length, error);
801   g_free (display_filename);
802
803   return retval;
804 }
805
806 #endif
807
808 /**
809  * g_file_get_contents:
810  * @filename: name of a file to read contents from, in the GLib file name encoding
811  * @contents: location to store an allocated string
812  * @length: location to store length in bytes of the contents, or %NULL
813  * @error: return location for a #GError, or %NULL
814  * 
815  * Reads an entire file into allocated memory, with good error
816  * checking. 
817  *
818  * If the call was successful, it returns %TRUE and sets @contents to the file 
819  * contents and @length to the length of the file contents in bytes. The string 
820  * stored in @contents will be nul-terminated, so for text files you can pass 
821  * %NULL for the @length argument. If the call was not successful, it returns 
822  * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error  
823  * codes are those in the #GFileError enumeration. In the error case, 
824  * @contents is set to %NULL and @length is set to zero.
825  *
826  * Return value: %TRUE on success, %FALSE if an error occurred
827  **/
828 gboolean
829 g_file_get_contents (const gchar *filename,
830                      gchar      **contents,
831                      gsize       *length,
832                      GError     **error)
833 {  
834   g_return_val_if_fail (filename != NULL, FALSE);
835   g_return_val_if_fail (contents != NULL, FALSE);
836
837   *contents = NULL;
838   if (length)
839     *length = 0;
840
841 #ifdef G_OS_WIN32
842   return get_contents_win32 (filename, contents, length, error);
843 #else
844   return get_contents_posix (filename, contents, length, error);
845 #endif
846 }
847
848 #ifdef G_OS_WIN32
849
850 #undef g_file_get_contents
851
852 /* Binary compatibility version. Not for newly compiled code. */
853
854 gboolean
855 g_file_get_contents (const gchar *filename,
856                      gchar      **contents,
857                      gsize       *length,
858                      GError     **error)
859 {
860   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
861   gboolean retval;
862
863   if (utf8_filename == NULL)
864     return FALSE;
865
866   retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
867
868   g_free (utf8_filename);
869
870   return retval;
871 }
872
873 #endif
874
875 static gboolean
876 rename_file (const char *old_name,
877              const char *new_name,
878              GError **err)
879 {
880   errno = 0;
881   if (g_rename (old_name, new_name) == -1)
882     {
883       int save_errno = errno;
884       gchar *display_old_name = g_filename_display_name (old_name);
885       gchar *display_new_name = g_filename_display_name (new_name);
886
887       g_set_error (err,
888                    G_FILE_ERROR,
889                    g_file_error_from_errno (save_errno),
890                    _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
891                    display_old_name,
892                    display_new_name,
893                    g_strerror (save_errno));
894
895       g_free (display_old_name);
896       g_free (display_new_name);
897       
898       return FALSE;
899     }
900   
901   return TRUE;
902 }
903
904 static gchar *
905 write_to_temp_file (const gchar *contents,
906                     gssize length,
907                     const gchar *template,
908                     GError **err)
909 {
910   gchar *tmp_name;
911   gchar *display_name;
912   gchar *retval;
913   FILE *file;
914   gint fd;
915   int save_errno;
916
917   retval = NULL;
918   
919   tmp_name = g_strdup_printf ("%s.XXXXXX", template);
920
921   errno = 0;
922   fd = create_temp_file (tmp_name, 0666);
923   display_name = g_filename_display_name (tmp_name);
924       
925   if (fd == -1)
926     {
927       save_errno = errno;
928       g_set_error (err,
929                    G_FILE_ERROR,
930                    g_file_error_from_errno (save_errno),
931                    _("Failed to create file '%s': %s"),
932                    display_name, g_strerror (save_errno));
933       
934       goto out;
935     }
936
937   errno = 0;
938   file = fdopen (fd, "wb");
939   if (!file)
940     {
941       save_errno = errno;
942       g_set_error (err,
943                    G_FILE_ERROR,
944                    g_file_error_from_errno (save_errno),
945                    _("Failed to open file '%s' for writing: fdopen() failed: %s"),
946                    display_name,
947                    g_strerror (save_errno));
948
949       close (fd);
950       g_unlink (tmp_name);
951       
952       goto out;
953     }
954
955   if (length > 0)
956     {
957       gsize n_written;
958       
959       errno = 0;
960
961       n_written = fwrite (contents, 1, length, file);
962
963       if (n_written < length)
964         {
965           save_errno = errno;
966       
967           g_set_error (err,
968                        G_FILE_ERROR,
969                        g_file_error_from_errno (save_errno),
970                        _("Failed to write file '%s': fwrite() failed: %s"),
971                        display_name,
972                        g_strerror (save_errno));
973
974           fclose (file);
975           g_unlink (tmp_name);
976           
977           goto out;
978         }
979     }
980    
981   errno = 0;
982   if (fclose (file) == EOF)
983     { 
984       save_errno = 0;
985       
986       g_set_error (err,
987                    G_FILE_ERROR,
988                    g_file_error_from_errno (save_errno),
989                    _("Failed to close file '%s': fclose() failed: %s"),
990                    display_name, 
991                    g_strerror (save_errno));
992
993       g_unlink (tmp_name);
994       
995       goto out;
996     }
997
998   retval = g_strdup (tmp_name);
999   
1000  out:
1001   g_free (tmp_name);
1002   g_free (display_name);
1003   
1004   return retval;
1005 }
1006
1007 /**
1008  * g_file_set_contents:
1009  * @filename: name of a file to write @contents to, in the GLib file name
1010  *   encoding
1011  * @contents: string to write to the file
1012  * @length: length of @contents, or -1 if @contents is a nul-terminated string
1013  * @error: return location for a #GError, or %NULL
1014  *
1015  * Writes all of @contents to a file named @filename, with good error checking.
1016  * If a file called @filename already exists it will be overwritten.
1017  *
1018  * This write is atomic in the sense that it is first written to a temporary
1019  * file which is then renamed to the final name. Notes:
1020  * <itemizedlist>
1021  * <listitem>
1022  *    On Unix, if @filename already exists hard links to @filename will break.
1023  *    Also since the file is recreated, existing permissions, access control
1024  *    lists, metadata etc. may be lost. If @filename is a symbolic link,
1025  *    the link itself will be replaced, not the linked file.
1026  * </listitem>
1027  * <listitem>
1028  *   On Windows renaming a file will not remove an existing file with the
1029  *   new name, so on Windows there is a race condition between the existing
1030  *   file being removed and the temporary file being renamed.
1031  * </listitem>
1032  * <listitem>
1033  *   On Windows there is no way to remove a file that is open to some
1034  *   process, or mapped into memory. Thus, this function will fail if
1035  *   @filename already exists and is open.
1036  * </listitem>
1037  * </itemizedlist>
1038  *
1039  * If the call was sucessful, it returns %TRUE. If the call was not successful,
1040  * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1041  * Possible error codes are those in the #GFileError enumeration.
1042  *
1043  * Return value: %TRUE on success, %FALSE if an error occurred
1044  *
1045  * Since: 2.8
1046  **/
1047 gboolean
1048 g_file_set_contents (const gchar *filename,
1049                      const gchar *contents,
1050                      gssize          length,
1051                      GError        **error)
1052 {
1053   gchar *tmp_filename;
1054   gboolean retval;
1055   GError *rename_error = NULL;
1056   
1057   g_return_val_if_fail (filename != NULL, FALSE);
1058   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1059   g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1060   g_return_val_if_fail (length >= -1, FALSE);
1061   
1062   if (length == -1)
1063     length = strlen (contents);
1064
1065   tmp_filename = write_to_temp_file (contents, length, filename, error);
1066   
1067   if (!tmp_filename)
1068     {
1069       retval = FALSE;
1070       goto out;
1071     }
1072
1073   if (!rename_file (tmp_filename, filename, &rename_error))
1074     {
1075 #ifndef G_OS_WIN32
1076
1077       g_unlink (tmp_filename);
1078       g_propagate_error (error, rename_error);
1079       retval = FALSE;
1080       goto out;
1081
1082 #else /* G_OS_WIN32 */
1083       
1084       /* Renaming failed, but on Windows this may just mean
1085        * the file already exists. So if the target file
1086        * exists, try deleting it and do the rename again.
1087        */
1088       if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1089         {
1090           g_unlink (tmp_filename);
1091           g_propagate_error (error, rename_error);
1092           retval = FALSE;
1093           goto out;
1094         }
1095
1096       g_error_free (rename_error);
1097       
1098       if (g_unlink (filename) == -1)
1099         {
1100           gchar *display_filename = g_filename_display_name (filename);
1101
1102           int save_errno = errno;
1103           
1104           g_set_error (error,
1105                        G_FILE_ERROR,
1106                        g_file_error_from_errno (save_errno),
1107                        _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1108                        display_filename,
1109                        g_strerror (save_errno));
1110
1111           g_free (display_filename);
1112           g_unlink (tmp_filename);
1113           retval = FALSE;
1114           goto out;
1115         }
1116       
1117       if (!rename_file (tmp_filename, filename, error))
1118         {
1119           g_unlink (tmp_filename);
1120           retval = FALSE;
1121           goto out;
1122         }
1123
1124 #endif
1125     }
1126
1127   retval = TRUE;
1128   
1129  out:
1130   g_free (tmp_filename);
1131   return retval;
1132 }
1133
1134 /*
1135  * create_temp_file based on the mkstemp implementation from the GNU C library.
1136  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1137  */
1138 static gint
1139 create_temp_file (gchar *tmpl, 
1140                   int    permissions)
1141 {
1142   char *XXXXXX;
1143   int count, fd;
1144   static const char letters[] =
1145     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1146   static const int NLETTERS = sizeof (letters) - 1;
1147   glong value;
1148   GTimeVal tv;
1149   static int counter = 0;
1150
1151   /* find the last occurrence of "XXXXXX" */
1152   XXXXXX = g_strrstr (tmpl, "XXXXXX");
1153
1154   if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1155     {
1156       errno = EINVAL;
1157       return -1;
1158     }
1159
1160   /* Get some more or less random data.  */
1161   g_get_current_time (&tv);
1162   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1163
1164   for (count = 0; count < 100; value += 7777, ++count)
1165     {
1166       glong v = value;
1167
1168       /* Fill in the random bits.  */
1169       XXXXXX[0] = letters[v % NLETTERS];
1170       v /= NLETTERS;
1171       XXXXXX[1] = letters[v % NLETTERS];
1172       v /= NLETTERS;
1173       XXXXXX[2] = letters[v % NLETTERS];
1174       v /= NLETTERS;
1175       XXXXXX[3] = letters[v % NLETTERS];
1176       v /= NLETTERS;
1177       XXXXXX[4] = letters[v % NLETTERS];
1178       v /= NLETTERS;
1179       XXXXXX[5] = letters[v % NLETTERS];
1180
1181       /* tmpl is in UTF-8 on Windows, thus use g_open() */
1182       fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, permissions);
1183
1184       if (fd >= 0)
1185         return fd;
1186       else if (errno != EEXIST)
1187         /* Any other error will apply also to other names we might
1188          *  try, and there are 2^32 or so of them, so give up now.
1189          */
1190         return -1;
1191     }
1192
1193   /* We got out of the loop because we ran out of combinations to try.  */
1194   errno = EEXIST;
1195   return -1;
1196 }
1197
1198 /**
1199  * g_mkstemp:
1200  * @tmpl: template filename
1201  *
1202  * Opens a temporary file. See the mkstemp() documentation
1203  * on most UNIX-like systems. 
1204  *
1205  * The parameter is a string that should follow the rules for
1206  * mkstemp() templates, i.e. contain the string "XXXXXX". 
1207  * g_mkstemp() is slightly more flexible than mkstemp()
1208  * in that the sequence does not have to occur at the very end of the 
1209  * template. The X string will 
1210  * be modified to form the name of a file that didn't exist.
1211  * The string should be in the GLib file name encoding. Most importantly, 
1212  * on Windows it should be in UTF-8.
1213  *
1214  * Return value: A file handle (as from open()) to the file
1215  * opened for reading and writing. The file is opened in binary mode
1216  * on platforms where there is a difference. The file handle should be
1217  * closed with close(). In case of errors, -1 is returned.  
1218  */ 
1219 gint
1220 g_mkstemp (gchar *tmpl)
1221 {
1222   return create_temp_file (tmpl, 0600);
1223 }
1224
1225 #ifdef G_OS_WIN32
1226
1227 #undef g_mkstemp
1228
1229 /* Binary compatibility version. Not for newly compiled code. */
1230
1231 gint
1232 g_mkstemp (gchar *tmpl)
1233 {
1234   char *XXXXXX;
1235   int count, fd;
1236   static const char letters[] =
1237     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1238   static const int NLETTERS = sizeof (letters) - 1;
1239   glong value;
1240   GTimeVal tv;
1241   static int counter = 0;
1242
1243   /* find the last occurrence of 'XXXXXX' */
1244   XXXXXX = g_strrstr (tmpl, "XXXXXX");
1245
1246   if (!XXXXXX || strcmp (XXXXXX, "XXXXXX"))
1247     {
1248       errno = EINVAL;
1249       return -1;
1250     }
1251
1252   /* Get some more or less random data.  */
1253   g_get_current_time (&tv);
1254   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1255
1256   for (count = 0; count < 100; value += 7777, ++count)
1257     {
1258       glong v = value;
1259
1260       /* Fill in the random bits.  */
1261       XXXXXX[0] = letters[v % NLETTERS];
1262       v /= NLETTERS;
1263       XXXXXX[1] = letters[v % NLETTERS];
1264       v /= NLETTERS;
1265       XXXXXX[2] = letters[v % NLETTERS];
1266       v /= NLETTERS;
1267       XXXXXX[3] = letters[v % NLETTERS];
1268       v /= NLETTERS;
1269       XXXXXX[4] = letters[v % NLETTERS];
1270       v /= NLETTERS;
1271       XXXXXX[5] = letters[v % NLETTERS];
1272
1273       /* This is the backward compatibility system codepage version,
1274        * thus use normal open().
1275        */
1276       fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1277
1278       if (fd >= 0)
1279         return fd;
1280       else if (errno != EEXIST)
1281         /* Any other error will apply also to other names we might
1282          *  try, and there are 2^32 or so of them, so give up now.
1283          */
1284         return -1;
1285     }
1286
1287   /* We got out of the loop because we ran out of combinations to try.  */
1288   errno = EEXIST;
1289   return -1;
1290 }
1291
1292 #endif
1293
1294 /**
1295  * g_file_open_tmp:
1296  * @tmpl: Template for file name, as in g_mkstemp(), basename only,
1297  *        or %NULL, to a default template
1298  * @name_used: location to store actual name used
1299  * @error: return location for a #GError
1300  *
1301  * Opens a file for writing in the preferred directory for temporary
1302  * files (as returned by g_get_tmp_dir()). 
1303  *
1304  * @tmpl should be a string in the GLib file name encoding containing 
1305  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1306  * However, unlike these functions, the template should only be a
1307  * basename, no directory components are allowed. If template is
1308  * %NULL, a default template is used.
1309  *
1310  * Note that in contrast to g_mkstemp() (and mkstemp()) 
1311  * @tmpl is not modified, and might thus be a read-only literal string.
1312  *
1313  * The actual name used is returned in @name_used if non-%NULL. This
1314  * string should be freed with g_free() when not needed any longer.
1315  * The returned name is in the GLib file name encoding.
1316  *
1317  * Return value: A file handle (as from open()) to 
1318  * the file opened for reading and writing. The file is opened in binary 
1319  * mode on platforms where there is a difference. The file handle should be
1320  * closed with close(). In case of errors, -1 is returned 
1321  * and @error will be set.
1322  **/
1323 gint
1324 g_file_open_tmp (const gchar *tmpl,
1325                  gchar      **name_used,
1326                  GError     **error)
1327 {
1328   int retval;
1329   const char *tmpdir;
1330   char *sep;
1331   char *fulltemplate;
1332   const char *slash;
1333
1334   if (tmpl == NULL)
1335     tmpl = ".XXXXXX";
1336
1337   if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1338 #ifdef G_OS_WIN32
1339       || (strchr (tmpl, '/') != NULL && (slash = "/"))
1340 #endif
1341       )
1342     {
1343       gchar *display_tmpl = g_filename_display_name (tmpl);
1344       char c[2];
1345       c[0] = *slash;
1346       c[1] = '\0';
1347
1348       g_set_error (error,
1349                    G_FILE_ERROR,
1350                    G_FILE_ERROR_FAILED,
1351                    _("Template '%s' invalid, should not contain a '%s'"),
1352                    display_tmpl, c);
1353       g_free (display_tmpl);
1354
1355       return -1;
1356     }
1357   
1358   if (strstr (tmpl, "XXXXXX") == NULL)
1359     {
1360       gchar *display_tmpl = g_filename_display_name (tmpl);
1361       g_set_error (error,
1362                    G_FILE_ERROR,
1363                    G_FILE_ERROR_FAILED,
1364                    _("Template '%s' doesn't contain XXXXXX"),
1365                    display_tmpl);
1366       g_free (display_tmpl);
1367       return -1;
1368     }
1369
1370   tmpdir = g_get_tmp_dir ();
1371
1372   if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1373     sep = "";
1374   else
1375     sep = G_DIR_SEPARATOR_S;
1376
1377   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1378
1379   retval = g_mkstemp (fulltemplate);
1380
1381   if (retval == -1)
1382     {
1383       int save_errno = errno;
1384       gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1385
1386       g_set_error (error,
1387                    G_FILE_ERROR,
1388                    g_file_error_from_errno (save_errno),
1389                    _("Failed to create file '%s': %s"),
1390                    display_fulltemplate, g_strerror (save_errno));
1391       g_free (display_fulltemplate);
1392       g_free (fulltemplate);
1393       return -1;
1394     }
1395
1396   if (name_used)
1397     *name_used = fulltemplate;
1398   else
1399     g_free (fulltemplate);
1400
1401   return retval;
1402 }
1403
1404 #ifdef G_OS_WIN32
1405
1406 #undef g_file_open_tmp
1407
1408 /* Binary compatibility version. Not for newly compiled code. */
1409
1410 gint
1411 g_file_open_tmp (const gchar *tmpl,
1412                  gchar      **name_used,
1413                  GError     **error)
1414 {
1415   gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1416   gchar *utf8_name_used;
1417   gint retval;
1418
1419   if (utf8_tmpl == NULL)
1420     return -1;
1421
1422   retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1423   
1424   if (retval == -1)
1425     return -1;
1426
1427   if (name_used)
1428     *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1429
1430   g_free (utf8_name_used);
1431
1432   return retval;
1433 }
1434
1435 #endif
1436
1437 static gchar *
1438 g_build_path_va (const gchar  *separator,
1439                  const gchar  *first_element,
1440                  va_list      *args,
1441                  gchar       **str_array)
1442 {
1443   GString *result;
1444   gint separator_len = strlen (separator);
1445   gboolean is_first = TRUE;
1446   gboolean have_leading = FALSE;
1447   const gchar *single_element = NULL;
1448   const gchar *next_element;
1449   const gchar *last_trailing = NULL;
1450   gint i = 0;
1451
1452   result = g_string_new (NULL);
1453
1454   if (str_array)
1455     next_element = str_array[i++];
1456   else
1457     next_element = first_element;
1458
1459   while (TRUE)
1460     {
1461       const gchar *element;
1462       const gchar *start;
1463       const gchar *end;
1464
1465       if (next_element)
1466         {
1467           element = next_element;
1468           if (str_array)
1469             next_element = str_array[i++];
1470           else
1471             next_element = va_arg (*args, gchar *);
1472         }
1473       else
1474         break;
1475
1476       /* Ignore empty elements */
1477       if (!*element)
1478         continue;
1479       
1480       start = element;
1481
1482       if (separator_len)
1483         {
1484           while (start &&
1485                  strncmp (start, separator, separator_len) == 0)
1486             start += separator_len;
1487         }
1488
1489       end = start + strlen (start);
1490       
1491       if (separator_len)
1492         {
1493           while (end >= start + separator_len &&
1494                  strncmp (end - separator_len, separator, separator_len) == 0)
1495             end -= separator_len;
1496           
1497           last_trailing = end;
1498           while (last_trailing >= element + separator_len &&
1499                  strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1500             last_trailing -= separator_len;
1501
1502           if (!have_leading)
1503             {
1504               /* If the leading and trailing separator strings are in the
1505                * same element and overlap, the result is exactly that element
1506                */
1507               if (last_trailing <= start)
1508                 single_element = element;
1509                   
1510               g_string_append_len (result, element, start - element);
1511               have_leading = TRUE;
1512             }
1513           else
1514             single_element = NULL;
1515         }
1516
1517       if (end == start)
1518         continue;
1519
1520       if (!is_first)
1521         g_string_append (result, separator);
1522       
1523       g_string_append_len (result, start, end - start);
1524       is_first = FALSE;
1525     }
1526
1527   if (single_element)
1528     {
1529       g_string_free (result, TRUE);
1530       return g_strdup (single_element);
1531     }
1532   else
1533     {
1534       if (last_trailing)
1535         g_string_append (result, last_trailing);
1536   
1537       return g_string_free (result, FALSE);
1538     }
1539 }
1540
1541 /**
1542  * g_build_pathv:
1543  * @separator: a string used to separator the elements of the path.
1544  * @args: %NULL-terminated array of strings containing the path elements.
1545  * 
1546  * Behaves exactly like g_build_path(), but takes the path elements 
1547  * as a string array, instead of varargs. This function is mainly
1548  * meant for language bindings.
1549  *
1550  * Return value: a newly-allocated string that must be freed with g_free().
1551  *
1552  * Since: 2.8
1553  */
1554 gchar *
1555 g_build_pathv (const gchar  *separator,
1556                gchar       **args)
1557 {
1558   if (!args)
1559     return NULL;
1560
1561   return g_build_path_va (separator, NULL, NULL, args);
1562 }
1563
1564
1565 /**
1566  * g_build_path:
1567  * @separator: a string used to separator the elements of the path.
1568  * @first_element: the first element in the path
1569  * @Varargs: remaining elements in path, terminated by %NULL
1570  * 
1571  * Creates a path from a series of elements using @separator as the
1572  * separator between elements. At the boundary between two elements,
1573  * any trailing occurrences of separator in the first element, or
1574  * leading occurrences of separator in the second element are removed
1575  * and exactly one copy of the separator is inserted.
1576  *
1577  * Empty elements are ignored.
1578  *
1579  * The number of leading copies of the separator on the result is
1580  * the same as the number of leading copies of the separator on
1581  * the first non-empty element.
1582  *
1583  * The number of trailing copies of the separator on the result is
1584  * the same as the number of trailing copies of the separator on
1585  * the last non-empty element. (Determination of the number of
1586  * trailing copies is done without stripping leading copies, so
1587  * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1588  * has 1 trailing copy.)
1589  *
1590  * However, if there is only a single non-empty element, and there
1591  * are no characters in that element not part of the leading or
1592  * trailing separators, then the result is exactly the original value
1593  * of that element.
1594  *
1595  * Other than for determination of the number of leading and trailing
1596  * copies of the separator, elements consisting only of copies
1597  * of the separator are ignored.
1598  * 
1599  * Return value: a newly-allocated string that must be freed with g_free().
1600  **/
1601 gchar *
1602 g_build_path (const gchar *separator,
1603               const gchar *first_element,
1604               ...)
1605 {
1606   gchar *str;
1607   va_list args;
1608
1609   g_return_val_if_fail (separator != NULL, NULL);
1610
1611   va_start (args, first_element);
1612   str = g_build_path_va (separator, first_element, &args, NULL);
1613   va_end (args);
1614
1615   return str;
1616 }
1617
1618 #ifdef G_OS_WIN32
1619
1620 static gchar *
1621 g_build_pathname_va (const gchar  *first_element,
1622                      va_list      *args,
1623                      gchar       **str_array)
1624 {
1625   /* Code copied from g_build_pathv(), and modified to use two
1626    * alternative single-character separators.
1627    */
1628   GString *result;
1629   gboolean is_first = TRUE;
1630   gboolean have_leading = FALSE;
1631   const gchar *single_element = NULL;
1632   const gchar *next_element;
1633   const gchar *last_trailing = NULL;
1634   gchar current_separator = '\\';
1635   gint i = 0;
1636
1637   result = g_string_new (NULL);
1638
1639   if (str_array)
1640     next_element = str_array[i++];
1641   else
1642     next_element = first_element;
1643   
1644   while (TRUE)
1645     {
1646       const gchar *element;
1647       const gchar *start;
1648       const gchar *end;
1649
1650       if (next_element)
1651         {
1652           element = next_element;
1653           if (str_array)
1654             next_element = str_array[i++];
1655           else
1656             next_element = va_arg (*args, gchar *);
1657         }
1658       else
1659         break;
1660
1661       /* Ignore empty elements */
1662       if (!*element)
1663         continue;
1664       
1665       start = element;
1666
1667       if (TRUE)
1668         {
1669           while (start &&
1670                  (*start == '\\' || *start == '/'))
1671             {
1672               current_separator = *start;
1673               start++;
1674             }
1675         }
1676
1677       end = start + strlen (start);
1678       
1679       if (TRUE)
1680         {
1681           while (end >= start + 1 &&
1682                  (end[-1] == '\\' || end[-1] == '/'))
1683             {
1684               current_separator = end[-1];
1685               end--;
1686             }
1687           
1688           last_trailing = end;
1689           while (last_trailing >= element + 1 &&
1690                  (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1691             last_trailing--;
1692
1693           if (!have_leading)
1694             {
1695               /* If the leading and trailing separator strings are in the
1696                * same element and overlap, the result is exactly that element
1697                */
1698               if (last_trailing <= start)
1699                 single_element = element;
1700                   
1701               g_string_append_len (result, element, start - element);
1702               have_leading = TRUE;
1703             }
1704           else
1705             single_element = NULL;
1706         }
1707
1708       if (end == start)
1709         continue;
1710
1711       if (!is_first)
1712         g_string_append_len (result, &current_separator, 1);
1713       
1714       g_string_append_len (result, start, end - start);
1715       is_first = FALSE;
1716     }
1717
1718   if (single_element)
1719     {
1720       g_string_free (result, TRUE);
1721       return g_strdup (single_element);
1722     }
1723   else
1724     {
1725       if (last_trailing)
1726         g_string_append (result, last_trailing);
1727   
1728       return g_string_free (result, FALSE);
1729     }
1730 }
1731
1732 #endif
1733
1734 /**
1735  * g_build_filenamev:
1736  * @args: %NULL-terminated array of strings containing the path elements.
1737  * 
1738  * Behaves exactly like g_build_filename(), but takes the path elements 
1739  * as a string array, instead of varargs. This function is mainly
1740  * meant for language bindings.
1741  *
1742  * Return value: a newly-allocated string that must be freed with g_free().
1743  * 
1744  * Since: 2.8
1745  */
1746 gchar *
1747 g_build_filenamev (gchar **args)
1748 {
1749   gchar *str;
1750
1751 #ifndef G_OS_WIN32
1752   str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1753 #else
1754   str = g_build_pathname_va (NULL, NULL, args);
1755 #endif
1756
1757   return str;
1758 }
1759
1760 /**
1761  * g_build_filename:
1762  * @first_element: the first element in the path
1763  * @Varargs: remaining elements in path, terminated by %NULL
1764  * 
1765  * Creates a filename from a series of elements using the correct
1766  * separator for filenames.
1767  *
1768  * On Unix, this function behaves identically to <literal>g_build_path
1769  * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1770  *
1771  * On Windows, it takes into account that either the backslash
1772  * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1773  * as separator in filenames, but otherwise behaves as on Unix. When
1774  * file pathname separators need to be inserted, the one that last
1775  * previously occurred in the parameters (reading from left to right)
1776  * is used.
1777  *
1778  * No attempt is made to force the resulting filename to be an absolute
1779  * path. If the first element is a relative path, the result will
1780  * be a relative path. 
1781  * 
1782  * Return value: a newly-allocated string that must be freed with g_free().
1783  **/
1784 gchar *
1785 g_build_filename (const gchar *first_element, 
1786                   ...)
1787 {
1788   gchar *str;
1789   va_list args;
1790
1791   va_start (args, first_element);
1792 #ifndef G_OS_WIN32
1793   str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1794 #else
1795   str = g_build_pathname_va (first_element, &args, NULL);
1796 #endif
1797   va_end (args);
1798
1799   return str;
1800 }
1801
1802 /**
1803  * g_file_read_link:
1804  * @filename: the symbolic link
1805  * @error: return location for a #GError
1806  *
1807  * Reads the contents of the symbolic link @filename like the POSIX
1808  * readlink() function.  The returned string is in the encoding used
1809  * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1810  *
1811  * Returns: A newly allocated string with the contents of the symbolic link, 
1812  *          or %NULL if an error occurred.
1813  *
1814  * Since: 2.4
1815  */
1816 gchar *
1817 g_file_read_link (const gchar *filename,
1818                   GError     **error)
1819 {
1820 #ifdef HAVE_READLINK
1821   gchar *buffer;
1822   guint size;
1823   gint read_size;    
1824   
1825   size = 256; 
1826   buffer = g_malloc (size);
1827   
1828   while (TRUE) 
1829     {
1830       read_size = readlink (filename, buffer, size);
1831       if (read_size < 0) {
1832         int save_errno = errno;
1833         gchar *display_filename = g_filename_display_name (filename);
1834
1835         g_free (buffer);
1836         g_set_error (error,
1837                      G_FILE_ERROR,
1838                      g_file_error_from_errno (save_errno),
1839                      _("Failed to read the symbolic link '%s': %s"),
1840                      display_filename, 
1841                      g_strerror (save_errno));
1842         g_free (display_filename);
1843         
1844         return NULL;
1845       }
1846     
1847       if (read_size < size) 
1848         {
1849           buffer[read_size] = 0;
1850           return buffer;
1851         }
1852       
1853       size *= 2;
1854       buffer = g_realloc (buffer, size);
1855     }
1856 #else
1857   g_set_error (error,
1858                G_FILE_ERROR,
1859                G_FILE_ERROR_INVAL,
1860                _("Symbolic links not supported"));
1861         
1862   return NULL;
1863 #endif
1864 }
1865
1866 #define __G_FILEUTILS_C__
1867 #include "galiasdef.c"