Add tests.
[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
195   if (G_WIN32_HAVE_WIDECHAR_API ())
196     {
197       wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
198
199       if (wfilename == NULL)
200         return FALSE;
201
202       attributes = GetFileAttributesW (wfilename);
203
204       g_free (wfilename);
205     }
206   else
207     {
208       gchar *cpfilename = g_locale_from_utf8 (filename, -1, NULL, NULL, NULL);
209
210       if (cpfilename == NULL)
211         return FALSE;
212       
213       attributes = GetFileAttributesA (cpfilename);
214       
215       g_free (cpfilename);
216     }
217
218   if (attributes == INVALID_FILE_ATTRIBUTES)
219     return FALSE;
220
221   if (test & G_FILE_TEST_EXISTS)
222     return TRUE;
223       
224   if (test & G_FILE_TEST_IS_REGULAR)
225     return (attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0;
226
227   if (test & G_FILE_TEST_IS_DIR)
228     return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
229
230   if (test & G_FILE_TEST_IS_EXECUTABLE)
231     {
232       const gchar *lastdot = strrchr (filename, '.');
233       const gchar *pathext = NULL, *p;
234       int extlen;
235
236       if (lastdot == NULL)
237         return FALSE;
238
239       if (stricmp (lastdot, ".exe") == 0 ||
240           stricmp (lastdot, ".cmd") == 0 ||
241           stricmp (lastdot, ".bat") == 0 ||
242           stricmp (lastdot, ".com") == 0)
243         return TRUE;
244
245       /* Check if it is one of the types listed in %PATHEXT% */
246
247       pathext = g_getenv ("PATHEXT");
248       if (pathext == NULL)
249         return FALSE;
250
251       pathext = g_utf8_casefold (pathext, -1);
252
253       lastdot = g_utf8_casefold (lastdot, -1);
254       extlen = strlen (lastdot);
255
256       p = pathext;
257       while (TRUE)
258         {
259           const gchar *q = strchr (p, ';');
260           if (q == NULL)
261             q = p + strlen (p);
262           if (extlen == q - p &&
263               memcmp (lastdot, p, extlen) == 0)
264             {
265               g_free ((gchar *) pathext);
266               g_free ((gchar *) lastdot);
267               return TRUE;
268             }
269           if (*q)
270             p = q + 1;
271           else
272             break;
273         }
274
275       g_free ((gchar *) pathext);
276       g_free ((gchar *) lastdot);
277       return FALSE;
278     }
279
280   return FALSE;
281 #else
282   if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
283     return TRUE;
284   
285   if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
286     {
287       if (getuid () != 0)
288         return TRUE;
289
290       /* For root, on some POSIX systems, access (filename, X_OK)
291        * will succeed even if no executable bits are set on the
292        * file. We fall through to a stat test to avoid that.
293        */
294     }
295   else
296     test &= ~G_FILE_TEST_IS_EXECUTABLE;
297
298   if (test & G_FILE_TEST_IS_SYMLINK)
299     {
300       struct stat s;
301
302       if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
303         return TRUE;
304     }
305   
306   if (test & (G_FILE_TEST_IS_REGULAR |
307               G_FILE_TEST_IS_DIR |
308               G_FILE_TEST_IS_EXECUTABLE))
309     {
310       struct stat s;
311       
312       if (stat (filename, &s) == 0)
313         {
314           if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
315             return TRUE;
316           
317           if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
318             return TRUE;
319
320           /* The extra test for root when access (file, X_OK) succeeds.
321            */
322           if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
323               ((s.st_mode & S_IXOTH) ||
324                (s.st_mode & S_IXUSR) ||
325                (s.st_mode & S_IXGRP)))
326             return TRUE;
327         }
328     }
329
330   return FALSE;
331 #endif
332 }
333
334 #ifdef G_OS_WIN32
335
336 #undef g_file_test
337
338 /* Binary compatibility version. Not for newly compiled code. */
339
340 gboolean
341 g_file_test (const gchar *filename,
342              GFileTest    test)
343 {
344   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
345   gboolean retval;
346
347   if (utf8_filename == NULL)
348     return FALSE;
349
350   retval = g_file_test_utf8 (utf8_filename, test);
351
352   g_free (utf8_filename);
353
354   return retval;
355 }
356
357 #endif
358
359 GQuark
360 g_file_error_quark (void)
361 {
362   return g_quark_from_static_string ("g-file-error-quark");
363 }
364
365 /**
366  * g_file_error_from_errno:
367  * @err_no: an "errno" value
368  * 
369  * Gets a #GFileError constant based on the passed-in @errno.
370  * For example, if you pass in %EEXIST this function returns
371  * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
372  * assume that all #GFileError values will exist.
373  *
374  * Normally a #GFileError value goes into a #GError returned
375  * from a function that manipulates files. So you would use
376  * g_file_error_from_errno() when constructing a #GError.
377  * 
378  * Return value: #GFileError corresponding to the given @errno
379  **/
380 GFileError
381 g_file_error_from_errno (gint err_no)
382 {
383   switch (err_no)
384     {
385 #ifdef EEXIST
386     case EEXIST:
387       return G_FILE_ERROR_EXIST;
388       break;
389 #endif
390
391 #ifdef EISDIR
392     case EISDIR:
393       return G_FILE_ERROR_ISDIR;
394       break;
395 #endif
396
397 #ifdef EACCES
398     case EACCES:
399       return G_FILE_ERROR_ACCES;
400       break;
401 #endif
402
403 #ifdef ENAMETOOLONG
404     case ENAMETOOLONG:
405       return G_FILE_ERROR_NAMETOOLONG;
406       break;
407 #endif
408
409 #ifdef ENOENT
410     case ENOENT:
411       return G_FILE_ERROR_NOENT;
412       break;
413 #endif
414
415 #ifdef ENOTDIR
416     case ENOTDIR:
417       return G_FILE_ERROR_NOTDIR;
418       break;
419 #endif
420
421 #ifdef ENXIO
422     case ENXIO:
423       return G_FILE_ERROR_NXIO;
424       break;
425 #endif
426
427 #ifdef ENODEV
428     case ENODEV:
429       return G_FILE_ERROR_NODEV;
430       break;
431 #endif
432
433 #ifdef EROFS
434     case EROFS:
435       return G_FILE_ERROR_ROFS;
436       break;
437 #endif
438
439 #ifdef ETXTBSY
440     case ETXTBSY:
441       return G_FILE_ERROR_TXTBSY;
442       break;
443 #endif
444
445 #ifdef EFAULT
446     case EFAULT:
447       return G_FILE_ERROR_FAULT;
448       break;
449 #endif
450
451 #ifdef ELOOP
452     case ELOOP:
453       return G_FILE_ERROR_LOOP;
454       break;
455 #endif
456
457 #ifdef ENOSPC
458     case ENOSPC:
459       return G_FILE_ERROR_NOSPC;
460       break;
461 #endif
462
463 #ifdef ENOMEM
464     case ENOMEM:
465       return G_FILE_ERROR_NOMEM;
466       break;
467 #endif
468
469 #ifdef EMFILE
470     case EMFILE:
471       return G_FILE_ERROR_MFILE;
472       break;
473 #endif
474
475 #ifdef ENFILE
476     case ENFILE:
477       return G_FILE_ERROR_NFILE;
478       break;
479 #endif
480
481 #ifdef EBADF
482     case EBADF:
483       return G_FILE_ERROR_BADF;
484       break;
485 #endif
486
487 #ifdef EINVAL
488     case EINVAL:
489       return G_FILE_ERROR_INVAL;
490       break;
491 #endif
492
493 #ifdef EPIPE
494     case EPIPE:
495       return G_FILE_ERROR_PIPE;
496       break;
497 #endif
498
499 #ifdef EAGAIN
500     case EAGAIN:
501       return G_FILE_ERROR_AGAIN;
502       break;
503 #endif
504
505 #ifdef EINTR
506     case EINTR:
507       return G_FILE_ERROR_INTR;
508       break;
509 #endif
510
511 #ifdef EIO
512     case EIO:
513       return G_FILE_ERROR_IO;
514       break;
515 #endif
516
517 #ifdef EPERM
518     case EPERM:
519       return G_FILE_ERROR_PERM;
520       break;
521 #endif
522
523 #ifdef ENOSYS
524     case ENOSYS:
525       return G_FILE_ERROR_NOSYS;
526       break;
527 #endif
528
529     default:
530       return G_FILE_ERROR_FAILED;
531       break;
532     }
533 }
534
535 static gboolean
536 get_contents_stdio (const gchar *display_filename,
537                     FILE        *f,
538                     gchar      **contents,
539                     gsize       *length,
540                     GError     **error)
541 {
542   gchar buf[4096];
543   size_t bytes;
544   gchar *str = NULL;
545   size_t total_bytes = 0;
546   size_t total_allocated = 0;
547   gchar *tmp;
548
549   g_assert (f != NULL);
550
551   while (!feof (f))
552     {
553       gint save_errno;
554
555       bytes = fread (buf, 1, sizeof (buf), f);
556       save_errno = errno;
557
558       while ((total_bytes + bytes + 1) > total_allocated)
559         {
560           if (str)
561             total_allocated *= 2;
562           else
563             total_allocated = MIN (bytes + 1, sizeof (buf));
564
565           tmp = g_try_realloc (str, total_allocated);
566
567           if (tmp == NULL)
568             {
569               g_set_error (error,
570                            G_FILE_ERROR,
571                            G_FILE_ERROR_NOMEM,
572                            _("Could not allocate %lu bytes to read file \"%s\""),
573                            (gulong) total_allocated,
574                            display_filename);
575
576               goto error;
577             }
578
579           str = tmp;
580         }
581
582       if (ferror (f))
583         {
584           g_set_error (error,
585                        G_FILE_ERROR,
586                        g_file_error_from_errno (save_errno),
587                        _("Error reading file '%s': %s"),
588                        display_filename,
589                        g_strerror (save_errno));
590
591           goto error;
592         }
593
594       memcpy (str + total_bytes, buf, bytes);
595       total_bytes += bytes;
596     }
597
598   fclose (f);
599
600   if (total_allocated == 0)
601     str = g_new (gchar, 1);
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   size_t bytes_read;
632   size_t size;
633   size_t 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 #ifdef G_OS_WIN32
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   display_name = g_filename_display_name (tmp_name);
939       
940   if (fd == -1)
941     {
942       save_errno = errno;
943       g_set_error (err,
944                    G_FILE_ERROR,
945                    g_file_error_from_errno (save_errno),
946                    _("Failed to create file '%s': %s"),
947                    display_name, g_strerror (save_errno));
948       
949       goto out;
950     }
951
952   errno = 0;
953   file = fdopen (fd, "wb");
954   if (!file)
955     {
956       save_errno = errno;
957       g_set_error (err,
958                    G_FILE_ERROR,
959                    g_file_error_from_errno (save_errno),
960                    _("Failed to open file '%s' for writing: fdopen() failed: %s"),
961                    display_name,
962                    g_strerror (save_errno));
963
964       close (fd);
965       g_unlink (tmp_name);
966       
967       goto out;
968     }
969
970   if (length > 0)
971     {
972       size_t n_written;
973       
974       errno = 0;
975
976       n_written = fwrite (contents, 1, length, file);
977
978       if (n_written < length)
979         {
980           save_errno = errno;
981       
982           g_set_error (err,
983                        G_FILE_ERROR,
984                        g_file_error_from_errno (save_errno),
985                        _("Failed to write file '%s': fwrite() failed: %s"),
986                        display_name,
987                        g_strerror (save_errno));
988
989           fclose (file);
990           g_unlink (tmp_name);
991           
992           goto out;
993         }
994     }
995    
996   errno = 0;
997   if (fclose (file) == EOF)
998     { 
999       save_errno = 0;
1000       
1001       g_set_error (err,
1002                    G_FILE_ERROR,
1003                    g_file_error_from_errno (save_errno),
1004                    _("Failed to close file '%s': fclose() failed: %s"),
1005                    display_name, 
1006                    g_strerror (save_errno));
1007
1008       g_unlink (tmp_name);
1009       
1010       goto out;
1011     }
1012
1013   retval = g_strdup (tmp_name);
1014   
1015  out:
1016   g_free (tmp_name);
1017   g_free (display_name);
1018   
1019   return retval;
1020 }
1021
1022 /**
1023  * g_file_set_contents:
1024  * @filename: name of a file to write @contents to, in the GLib file name
1025  *   encoding
1026  * @contents: string to write to the file
1027  * @length: length of @contents, or -1 if @contents is a nul-terminated string
1028  * @error: return location for a #GError, or %NULL
1029  *
1030  * Writes all of @contents to a file named @filename, with good error checking.
1031  * If a file called @filename already exists it will be overwritten.
1032  *
1033  * This write is atomic in the sense that it is first written to a temporary
1034  * file which is then renamed to the final name. Notes:
1035  * <itemizedlist>
1036  * <listitem>
1037  *    On Unix, if @filename already exists hard links to @filename will break.
1038  *    Also since the file is recreated, existing permissions, access control
1039  *    lists, metadata etc. may be lost. If @filename is a symbolic link,
1040  *    the link itself will be replaced, not the linked file.
1041  * </listitem>
1042  * <listitem>
1043  *   On Windows renaming a file will not remove an existing file with the
1044  *   new name, so on Windows there is a race condition between the existing
1045  *   file being removed and the temporary file being renamed.
1046  * </listitem>
1047  * <listitem>
1048  *   On Windows there is no way to remove a file that is open to some
1049  *   process, or mapped into memory. Thus, this function will fail if
1050  *   @filename already exists and is open.
1051  * </listitem>
1052  * </itemizedlist>
1053  *
1054  * If the call was sucessful, it returns %TRUE. If the call was not successful,
1055  * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1056  * Possible error codes are those in the #GFileError enumeration.
1057  *
1058  * Return value: %TRUE on success, %FALSE if an error occurred
1059  *
1060  * Since: 2.8
1061  **/
1062 gboolean
1063 g_file_set_contents (const gchar *filename,
1064                      const gchar *contents,
1065                      gssize          length,
1066                      GError        **error)
1067 {
1068   gchar *tmp_filename;
1069   gboolean retval;
1070   GError *rename_error = NULL;
1071   
1072   g_return_val_if_fail (filename != NULL, FALSE);
1073   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1074   g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1075   g_return_val_if_fail (length >= -1, FALSE);
1076   
1077   if (length == -1)
1078     length = strlen (contents);
1079
1080   tmp_filename = write_to_temp_file (contents, length, filename, error);
1081   
1082   if (!tmp_filename)
1083     {
1084       retval = FALSE;
1085       goto out;
1086     }
1087
1088   if (!rename_file (tmp_filename, filename, &rename_error))
1089     {
1090 #ifndef G_OS_WIN32
1091
1092       g_unlink (tmp_filename);
1093       g_propagate_error (error, rename_error);
1094       retval = FALSE;
1095       goto out;
1096
1097 #else /* G_OS_WIN32 */
1098       
1099       /* Renaming failed, but on Windows this may just mean
1100        * the file already exists. So if the target file
1101        * exists, try deleting it and do the rename again.
1102        */
1103       if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1104         {
1105           g_unlink (tmp_filename);
1106           g_propagate_error (error, rename_error);
1107           retval = FALSE;
1108           goto out;
1109         }
1110
1111       g_error_free (rename_error);
1112       
1113       if (g_unlink (filename) == -1)
1114         {
1115           gchar *display_filename = g_filename_display_name (filename);
1116
1117           int save_errno = errno;
1118           
1119           g_set_error (error,
1120                        G_FILE_ERROR,
1121                        g_file_error_from_errno (save_errno),
1122                        _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1123                        display_filename,
1124                        g_strerror (save_errno));
1125
1126           g_free (display_filename);
1127           g_unlink (tmp_filename);
1128           retval = FALSE;
1129           goto out;
1130         }
1131       
1132       if (!rename_file (tmp_filename, filename, error))
1133         {
1134           g_unlink (tmp_filename);
1135           retval = FALSE;
1136           goto out;
1137         }
1138
1139 #endif
1140     }
1141
1142   retval = TRUE;
1143   
1144  out:
1145   g_free (tmp_filename);
1146   return retval;
1147 }
1148
1149 /*
1150  * create_temp_file based on the mkstemp implementation from the GNU C library.
1151  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1152  */
1153 static gint
1154 create_temp_file (gchar *tmpl, 
1155                   int    permissions)
1156 {
1157   char *XXXXXX;
1158   int count, fd;
1159   static const char letters[] =
1160     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1161   static const int NLETTERS = sizeof (letters) - 1;
1162   glong value;
1163   GTimeVal tv;
1164   static int counter = 0;
1165
1166   /* find the last occurrence of "XXXXXX" */
1167   XXXXXX = g_strrstr (tmpl, "XXXXXX");
1168
1169   if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1170     {
1171       errno = EINVAL;
1172       return -1;
1173     }
1174
1175   /* Get some more or less random data.  */
1176   g_get_current_time (&tv);
1177   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1178
1179   for (count = 0; count < 100; value += 7777, ++count)
1180     {
1181       glong v = value;
1182
1183       /* Fill in the random bits.  */
1184       XXXXXX[0] = letters[v % NLETTERS];
1185       v /= NLETTERS;
1186       XXXXXX[1] = letters[v % NLETTERS];
1187       v /= NLETTERS;
1188       XXXXXX[2] = letters[v % NLETTERS];
1189       v /= NLETTERS;
1190       XXXXXX[3] = letters[v % NLETTERS];
1191       v /= NLETTERS;
1192       XXXXXX[4] = letters[v % NLETTERS];
1193       v /= NLETTERS;
1194       XXXXXX[5] = letters[v % NLETTERS];
1195
1196       /* tmpl is in UTF-8 on Windows, thus use g_open() */
1197       fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, permissions);
1198
1199       if (fd >= 0)
1200         return fd;
1201       else if (errno != EEXIST)
1202         /* Any other error will apply also to other names we might
1203          *  try, and there are 2^32 or so of them, so give up now.
1204          */
1205         return -1;
1206     }
1207
1208   /* We got out of the loop because we ran out of combinations to try.  */
1209   errno = EEXIST;
1210   return -1;
1211 }
1212
1213 /**
1214  * g_mkstemp:
1215  * @tmpl: template filename
1216  *
1217  * Opens a temporary file. See the mkstemp() documentation
1218  * on most UNIX-like systems. 
1219  *
1220  * The parameter is a string that should follow the rules for
1221  * mkstemp() templates, i.e. contain the string "XXXXXX". 
1222  * g_mkstemp() is slightly more flexible than mkstemp()
1223  * in that the sequence does not have to occur at the very end of the 
1224  * template. The X string will 
1225  * be modified to form the name of a file that didn't exist.
1226  * The string should be in the GLib file name encoding. Most importantly, 
1227  * on Windows it should be in UTF-8.
1228  *
1229  * Return value: A file handle (as from open()) to the file
1230  * opened for reading and writing. The file is opened in binary mode
1231  * on platforms where there is a difference. The file handle should be
1232  * closed with close(). In case of errors, -1 is returned.  
1233  */ 
1234 gint
1235 g_mkstemp (gchar *tmpl)
1236 {
1237   return create_temp_file (tmpl, 0600);
1238 }
1239
1240 #ifdef G_OS_WIN32
1241
1242 #undef g_mkstemp
1243
1244 /* Binary compatibility version. Not for newly compiled code. */
1245
1246 gint
1247 g_mkstemp (gchar *tmpl)
1248 {
1249   char *XXXXXX;
1250   int count, fd;
1251   static const char letters[] =
1252     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1253   static const int NLETTERS = sizeof (letters) - 1;
1254   glong value;
1255   GTimeVal tv;
1256   static int counter = 0;
1257
1258   /* find the last occurrence of 'XXXXXX' */
1259   XXXXXX = g_strrstr (tmpl, "XXXXXX");
1260
1261   if (!XXXXXX || strcmp (XXXXXX, "XXXXXX"))
1262     {
1263       errno = EINVAL;
1264       return -1;
1265     }
1266
1267   /* Get some more or less random data.  */
1268   g_get_current_time (&tv);
1269   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1270
1271   for (count = 0; count < 100; value += 7777, ++count)
1272     {
1273       glong v = value;
1274
1275       /* Fill in the random bits.  */
1276       XXXXXX[0] = letters[v % NLETTERS];
1277       v /= NLETTERS;
1278       XXXXXX[1] = letters[v % NLETTERS];
1279       v /= NLETTERS;
1280       XXXXXX[2] = letters[v % NLETTERS];
1281       v /= NLETTERS;
1282       XXXXXX[3] = letters[v % NLETTERS];
1283       v /= NLETTERS;
1284       XXXXXX[4] = letters[v % NLETTERS];
1285       v /= NLETTERS;
1286       XXXXXX[5] = letters[v % NLETTERS];
1287
1288       /* This is the backward compatibility system codepage version,
1289        * thus use normal open().
1290        */
1291       fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1292
1293       if (fd >= 0)
1294         return fd;
1295       else if (errno != EEXIST)
1296         /* Any other error will apply also to other names we might
1297          *  try, and there are 2^32 or so of them, so give up now.
1298          */
1299         return -1;
1300     }
1301
1302   /* We got out of the loop because we ran out of combinations to try.  */
1303   errno = EEXIST;
1304   return -1;
1305 }
1306
1307 #endif
1308
1309 /**
1310  * g_file_open_tmp:
1311  * @tmpl: Template for file name, as in g_mkstemp(), basename only,
1312  *        or %NULL, to a default template
1313  * @name_used: location to store actual name used
1314  * @error: return location for a #GError
1315  *
1316  * Opens a file for writing in the preferred directory for temporary
1317  * files (as returned by g_get_tmp_dir()). 
1318  *
1319  * @tmpl should be a string in the GLib file name encoding containing 
1320  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1321  * However, unlike these functions, the template should only be a
1322  * basename, no directory components are allowed. If template is
1323  * %NULL, a default template is used.
1324  *
1325  * Note that in contrast to g_mkstemp() (and mkstemp()) 
1326  * @tmpl is not modified, and might thus be a read-only literal string.
1327  *
1328  * The actual name used is returned in @name_used if non-%NULL. This
1329  * string should be freed with g_free() when not needed any longer.
1330  * The returned name is in the GLib file name encoding.
1331  *
1332  * Return value: A file handle (as from open()) to 
1333  * the file opened for reading and writing. The file is opened in binary 
1334  * mode on platforms where there is a difference. The file handle should be
1335  * closed with close(). In case of errors, -1 is returned 
1336  * and @error will be set.
1337  **/
1338 gint
1339 g_file_open_tmp (const gchar *tmpl,
1340                  gchar      **name_used,
1341                  GError     **error)
1342 {
1343   int retval;
1344   const char *tmpdir;
1345   char *sep;
1346   char *fulltemplate;
1347   const char *slash;
1348
1349   if (tmpl == NULL)
1350     tmpl = ".XXXXXX";
1351
1352   if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1353 #ifdef G_OS_WIN32
1354       || (strchr (tmpl, '/') != NULL && (slash = "/"))
1355 #endif
1356       )
1357     {
1358       gchar *display_tmpl = g_filename_display_name (tmpl);
1359       char c[2];
1360       c[0] = *slash;
1361       c[1] = '\0';
1362
1363       g_set_error (error,
1364                    G_FILE_ERROR,
1365                    G_FILE_ERROR_FAILED,
1366                    _("Template '%s' invalid, should not contain a '%s'"),
1367                    display_tmpl, c);
1368       g_free (display_tmpl);
1369
1370       return -1;
1371     }
1372   
1373   if (strstr (tmpl, "XXXXXX") == NULL)
1374     {
1375       gchar *display_tmpl = g_filename_display_name (tmpl);
1376       g_set_error (error,
1377                    G_FILE_ERROR,
1378                    G_FILE_ERROR_FAILED,
1379                    _("Template '%s' doesn't contain XXXXXX"),
1380                    display_tmpl);
1381       g_free (display_tmpl);
1382       return -1;
1383     }
1384
1385   tmpdir = g_get_tmp_dir ();
1386
1387   if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1388     sep = "";
1389   else
1390     sep = G_DIR_SEPARATOR_S;
1391
1392   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1393
1394   retval = g_mkstemp (fulltemplate);
1395
1396   if (retval == -1)
1397     {
1398       int save_errno = errno;
1399       gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1400
1401       g_set_error (error,
1402                    G_FILE_ERROR,
1403                    g_file_error_from_errno (save_errno),
1404                    _("Failed to create file '%s': %s"),
1405                    display_fulltemplate, g_strerror (save_errno));
1406       g_free (display_fulltemplate);
1407       g_free (fulltemplate);
1408       return -1;
1409     }
1410
1411   if (name_used)
1412     *name_used = fulltemplate;
1413   else
1414     g_free (fulltemplate);
1415
1416   return retval;
1417 }
1418
1419 #ifdef G_OS_WIN32
1420
1421 #undef g_file_open_tmp
1422
1423 /* Binary compatibility version. Not for newly compiled code. */
1424
1425 gint
1426 g_file_open_tmp (const gchar *tmpl,
1427                  gchar      **name_used,
1428                  GError     **error)
1429 {
1430   gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1431   gchar *utf8_name_used;
1432   gint retval;
1433
1434   if (utf8_tmpl == NULL)
1435     return -1;
1436
1437   retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1438   
1439   if (retval == -1)
1440     return -1;
1441
1442   if (name_used)
1443     *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1444
1445   g_free (utf8_name_used);
1446
1447   return retval;
1448 }
1449
1450 #endif
1451
1452 static gchar *
1453 g_build_path_va (const gchar  *separator,
1454                  const gchar  *first_element,
1455                  va_list      *args,
1456                  gchar       **str_array)
1457 {
1458   GString *result;
1459   gint separator_len = strlen (separator);
1460   gboolean is_first = TRUE;
1461   gboolean have_leading = FALSE;
1462   const gchar *single_element = NULL;
1463   const gchar *next_element;
1464   const gchar *last_trailing = NULL;
1465   gint i = 0;
1466
1467   result = g_string_new (NULL);
1468
1469   if (str_array)
1470     next_element = str_array[i++];
1471   else
1472     next_element = first_element;
1473
1474   while (TRUE)
1475     {
1476       const gchar *element;
1477       const gchar *start;
1478       const gchar *end;
1479
1480       if (next_element)
1481         {
1482           element = next_element;
1483           if (str_array)
1484             next_element = str_array[i++];
1485           else
1486             next_element = va_arg (*args, gchar *);
1487         }
1488       else
1489         break;
1490
1491       /* Ignore empty elements */
1492       if (!*element)
1493         continue;
1494       
1495       start = element;
1496
1497       if (separator_len)
1498         {
1499           while (start &&
1500                  strncmp (start, separator, separator_len) == 0)
1501             start += separator_len;
1502         }
1503
1504       end = start + strlen (start);
1505       
1506       if (separator_len)
1507         {
1508           while (end >= start + separator_len &&
1509                  strncmp (end - separator_len, separator, separator_len) == 0)
1510             end -= separator_len;
1511           
1512           last_trailing = end;
1513           while (last_trailing >= element + separator_len &&
1514                  strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1515             last_trailing -= separator_len;
1516
1517           if (!have_leading)
1518             {
1519               /* If the leading and trailing separator strings are in the
1520                * same element and overlap, the result is exactly that element
1521                */
1522               if (last_trailing <= start)
1523                 single_element = element;
1524                   
1525               g_string_append_len (result, element, start - element);
1526               have_leading = TRUE;
1527             }
1528           else
1529             single_element = NULL;
1530         }
1531
1532       if (end == start)
1533         continue;
1534
1535       if (!is_first)
1536         g_string_append (result, separator);
1537       
1538       g_string_append_len (result, start, end - start);
1539       is_first = FALSE;
1540     }
1541
1542   if (single_element)
1543     {
1544       g_string_free (result, TRUE);
1545       return g_strdup (single_element);
1546     }
1547   else
1548     {
1549       if (last_trailing)
1550         g_string_append (result, last_trailing);
1551   
1552       return g_string_free (result, FALSE);
1553     }
1554 }
1555
1556 /**
1557  * g_build_pathv:
1558  * @separator: a string used to separator the elements of the path.
1559  * @args: %NULL-terminated array of strings containing the path elements.
1560  * 
1561  * Behaves exactly like g_build_path(), but takes the path elements 
1562  * as a string array, instead of varargs. This function is mainly
1563  * meant for language bindings.
1564  *
1565  * Return value: a newly-allocated string that must be freed with g_free().
1566  *
1567  * Since: 2.8
1568  */
1569 gchar *
1570 g_build_pathv (const gchar  *separator,
1571                gchar       **args)
1572 {
1573   if (!args)
1574     return NULL;
1575
1576   return g_build_path_va (separator, NULL, NULL, args);
1577 }
1578
1579
1580 /**
1581  * g_build_path:
1582  * @separator: a string used to separator the elements of the path.
1583  * @first_element: the first element in the path
1584  * @Varargs: remaining elements in path, terminated by %NULL
1585  * 
1586  * Creates a path from a series of elements using @separator as the
1587  * separator between elements. At the boundary between two elements,
1588  * any trailing occurrences of separator in the first element, or
1589  * leading occurrences of separator in the second element are removed
1590  * and exactly one copy of the separator is inserted.
1591  *
1592  * Empty elements are ignored.
1593  *
1594  * The number of leading copies of the separator on the result is
1595  * the same as the number of leading copies of the separator on
1596  * the first non-empty element.
1597  *
1598  * The number of trailing copies of the separator on the result is
1599  * the same as the number of trailing copies of the separator on
1600  * the last non-empty element. (Determination of the number of
1601  * trailing copies is done without stripping leading copies, so
1602  * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1603  * has 1 trailing copy.)
1604  *
1605  * However, if there is only a single non-empty element, and there
1606  * are no characters in that element not part of the leading or
1607  * trailing separators, then the result is exactly the original value
1608  * of that element.
1609  *
1610  * Other than for determination of the number of leading and trailing
1611  * copies of the separator, elements consisting only of copies
1612  * of the separator are ignored.
1613  * 
1614  * Return value: a newly-allocated string that must be freed with g_free().
1615  **/
1616 gchar *
1617 g_build_path (const gchar *separator,
1618               const gchar *first_element,
1619               ...)
1620 {
1621   gchar *str;
1622   va_list args;
1623
1624   g_return_val_if_fail (separator != NULL, NULL);
1625
1626   va_start (args, first_element);
1627   str = g_build_path_va (separator, first_element, &args, NULL);
1628   va_end (args);
1629
1630   return str;
1631 }
1632
1633 #ifdef G_OS_WIN32
1634
1635 static gchar *
1636 g_build_pathname_va (const gchar  *first_element,
1637                      va_list      *args,
1638                      gchar       **str_array)
1639 {
1640   /* Code copied from g_build_pathv(), and modified to use two
1641    * alternative single-character separators.
1642    */
1643   GString *result;
1644   gboolean is_first = TRUE;
1645   gboolean have_leading = FALSE;
1646   const gchar *single_element = NULL;
1647   const gchar *next_element;
1648   const gchar *last_trailing = NULL;
1649   gchar current_separator = '\\';
1650   gint i = 0;
1651
1652   result = g_string_new (NULL);
1653
1654   if (str_array)
1655     next_element = str_array[i++];
1656   else
1657     next_element = first_element;
1658   
1659   while (TRUE)
1660     {
1661       const gchar *element;
1662       const gchar *start;
1663       const gchar *end;
1664
1665       if (next_element)
1666         {
1667           element = next_element;
1668           if (str_array)
1669             next_element = str_array[i++];
1670           else
1671             next_element = va_arg (*args, gchar *);
1672         }
1673       else
1674         break;
1675
1676       /* Ignore empty elements */
1677       if (!*element)
1678         continue;
1679       
1680       start = element;
1681
1682       if (TRUE)
1683         {
1684           while (start &&
1685                  (*start == '\\' || *start == '/'))
1686             {
1687               current_separator = *start;
1688               start++;
1689             }
1690         }
1691
1692       end = start + strlen (start);
1693       
1694       if (TRUE)
1695         {
1696           while (end >= start + 1 &&
1697                  (end[-1] == '\\' || end[-1] == '/'))
1698             {
1699               current_separator = end[-1];
1700               end--;
1701             }
1702           
1703           last_trailing = end;
1704           while (last_trailing >= element + 1 &&
1705                  (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1706             last_trailing--;
1707
1708           if (!have_leading)
1709             {
1710               /* If the leading and trailing separator strings are in the
1711                * same element and overlap, the result is exactly that element
1712                */
1713               if (last_trailing <= start)
1714                 single_element = element;
1715                   
1716               g_string_append_len (result, element, start - element);
1717               have_leading = TRUE;
1718             }
1719           else
1720             single_element = NULL;
1721         }
1722
1723       if (end == start)
1724         continue;
1725
1726       if (!is_first)
1727         g_string_append_len (result, &current_separator, 1);
1728       
1729       g_string_append_len (result, start, end - start);
1730       is_first = FALSE;
1731     }
1732
1733   if (single_element)
1734     {
1735       g_string_free (result, TRUE);
1736       return g_strdup (single_element);
1737     }
1738   else
1739     {
1740       if (last_trailing)
1741         g_string_append (result, last_trailing);
1742   
1743       return g_string_free (result, FALSE);
1744     }
1745 }
1746
1747 #endif
1748
1749 /**
1750  * g_build_filenamev:
1751  * @args: %NULL-terminated array of strings containing the path elements.
1752  * 
1753  * Behaves exactly like g_build_filename(), but takes the path elements 
1754  * as a string array, instead of varargs. This function is mainly
1755  * meant for language bindings.
1756  *
1757  * Return value: a newly-allocated string that must be freed with g_free().
1758  * 
1759  * Since: 2.8
1760  */
1761 gchar *
1762 g_build_filenamev (gchar **args)
1763 {
1764   gchar *str;
1765
1766 #ifndef G_OS_WIN32
1767   str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1768 #else
1769   str = g_build_pathname_va (NULL, NULL, args);
1770 #endif
1771
1772   return str;
1773 }
1774
1775 /**
1776  * g_build_filename:
1777  * @first_element: the first element in the path
1778  * @Varargs: remaining elements in path, terminated by %NULL
1779  * 
1780  * Creates a filename from a series of elements using the correct
1781  * separator for filenames.
1782  *
1783  * On Unix, this function behaves identically to <literal>g_build_path
1784  * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1785  *
1786  * On Windows, it takes into account that either the backslash
1787  * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1788  * as separator in filenames, but otherwise behaves as on Unix. When
1789  * file pathname separators need to be inserted, the one that last
1790  * previously occurred in the parameters (reading from left to right)
1791  * is used.
1792  *
1793  * No attempt is made to force the resulting filename to be an absolute
1794  * path. If the first element is a relative path, the result will
1795  * be a relative path. 
1796  * 
1797  * Return value: a newly-allocated string that must be freed with g_free().
1798  **/
1799 gchar *
1800 g_build_filename (const gchar *first_element, 
1801                   ...)
1802 {
1803   gchar *str;
1804   va_list args;
1805
1806   va_start (args, first_element);
1807 #ifndef G_OS_WIN32
1808   str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1809 #else
1810   str = g_build_pathname_va (first_element, &args, NULL);
1811 #endif
1812   va_end (args);
1813
1814   return str;
1815 }
1816
1817 /**
1818  * g_file_read_link:
1819  * @filename: the symbolic link
1820  * @error: return location for a #GError
1821  *
1822  * Reads the contents of the symbolic link @filename like the POSIX
1823  * readlink() function.  The returned string is in the encoding used
1824  * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1825  *
1826  * Returns: A newly allocated string with the contents of the symbolic link, 
1827  *          or %NULL if an error occurred.
1828  *
1829  * Since: 2.4
1830  */
1831 gchar *
1832 g_file_read_link (const gchar *filename,
1833                   GError     **error)
1834 {
1835 #ifdef HAVE_READLINK
1836   gchar *buffer;
1837   guint size;
1838   gint read_size;    
1839   
1840   size = 256; 
1841   buffer = g_malloc (size);
1842   
1843   while (TRUE) 
1844     {
1845       read_size = readlink (filename, buffer, size);
1846       if (read_size < 0) {
1847         int save_errno = errno;
1848         gchar *display_filename = g_filename_display_name (filename);
1849
1850         g_free (buffer);
1851         g_set_error (error,
1852                      G_FILE_ERROR,
1853                      g_file_error_from_errno (save_errno),
1854                      _("Failed to read the symbolic link '%s': %s"),
1855                      display_filename, 
1856                      g_strerror (save_errno));
1857         g_free (display_filename);
1858         
1859         return NULL;
1860       }
1861     
1862       if (read_size < size) 
1863         {
1864           buffer[read_size] = 0;
1865           return buffer;
1866         }
1867       
1868       size *= 2;
1869       buffer = g_realloc (buffer, size);
1870     }
1871 #else
1872   g_set_error (error,
1873                G_FILE_ERROR,
1874                G_FILE_ERROR_INVAL,
1875                _("Symbolic links not supported"));
1876         
1877   return NULL;
1878 #endif
1879 }
1880
1881 #define __G_FILEUTILS_C__
1882 #include "galiasdef.c"