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