Move short_month_names and long_month_names to bss.
[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   int len;
1158   char *XXXXXX;
1159   int count, fd;
1160   static const char letters[] =
1161     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1162   static const int NLETTERS = sizeof (letters) - 1;
1163   glong value;
1164   GTimeVal tv;
1165   static int counter = 0;
1166
1167   len = strlen (tmpl);
1168   if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
1169     {
1170       errno = EINVAL;
1171       return -1;
1172     }
1173
1174   /* This is where the Xs start.  */
1175   XXXXXX = &tmpl[len - 6];
1176
1177   /* Get some more or less random data.  */
1178   g_get_current_time (&tv);
1179   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1180
1181   for (count = 0; count < 100; value += 7777, ++count)
1182     {
1183       glong v = value;
1184
1185       /* Fill in the random bits.  */
1186       XXXXXX[0] = letters[v % NLETTERS];
1187       v /= NLETTERS;
1188       XXXXXX[1] = letters[v % NLETTERS];
1189       v /= NLETTERS;
1190       XXXXXX[2] = letters[v % NLETTERS];
1191       v /= NLETTERS;
1192       XXXXXX[3] = letters[v % NLETTERS];
1193       v /= NLETTERS;
1194       XXXXXX[4] = letters[v % NLETTERS];
1195       v /= NLETTERS;
1196       XXXXXX[5] = letters[v % NLETTERS];
1197
1198       /* tmpl is in UTF-8 on Windows, thus use g_open() */
1199       fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, permissions);
1200
1201       if (fd >= 0)
1202         return fd;
1203       else if (errno != EEXIST)
1204         /* Any other error will apply also to other names we might
1205          *  try, and there are 2^32 or so of them, so give up now.
1206          */
1207         return -1;
1208     }
1209
1210   /* We got out of the loop because we ran out of combinations to try.  */
1211   errno = EEXIST;
1212   return -1;
1213 }
1214
1215 /**
1216  * g_mkstemp:
1217  * @tmpl: template filename
1218  *
1219  * Opens a temporary file. See the mkstemp() documentation
1220  * on most UNIX-like systems. This is a portability wrapper, which simply calls 
1221  * mkstemp() on systems that have it, and implements 
1222  * it in GLib otherwise.
1223  *
1224  * The parameter is a string that should match the rules for
1225  * mkstemp(), i.e. end in "XXXXXX". The X string will 
1226  * be modified to form the name of a file that didn't exist.
1227  * The string should be in the GLib file name encoding. Most importantly, 
1228  * on Windows it should be in UTF-8.
1229  *
1230  * Return value: A file handle (as from open()) to the file
1231  * opened for reading and writing. The file is opened in binary mode
1232  * on platforms where there is a difference. The file handle should be
1233  * closed with close(). In case of errors, -1 is returned.
1234  */
1235 gint
1236 g_mkstemp (gchar *tmpl)
1237 {
1238 #ifdef HAVE_MKSTEMP
1239   return mkstemp (tmpl);
1240 #else
1241   return create_temp_file (tmpl, 0600);
1242 #endif
1243 }
1244
1245 #ifdef G_OS_WIN32
1246
1247 #undef g_mkstemp
1248
1249 /* Binary compatibility version. Not for newly compiled code. */
1250
1251 gint
1252 g_mkstemp (gchar *tmpl)
1253 {
1254   int len;
1255   char *XXXXXX;
1256   int count, fd;
1257   static const char letters[] =
1258     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1259   static const int NLETTERS = sizeof (letters) - 1;
1260   glong value;
1261   GTimeVal tv;
1262   static int counter = 0;
1263
1264   len = strlen (tmpl);
1265   if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
1266     {
1267       errno = EINVAL;
1268       return -1;
1269     }
1270
1271   /* This is where the Xs start.  */
1272   XXXXXX = &tmpl[len - 6];
1273
1274   /* Get some more or less random data.  */
1275   g_get_current_time (&tv);
1276   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1277
1278   for (count = 0; count < 100; value += 7777, ++count)
1279     {
1280       glong v = value;
1281
1282       /* Fill in the random bits.  */
1283       XXXXXX[0] = letters[v % NLETTERS];
1284       v /= NLETTERS;
1285       XXXXXX[1] = letters[v % NLETTERS];
1286       v /= NLETTERS;
1287       XXXXXX[2] = letters[v % NLETTERS];
1288       v /= NLETTERS;
1289       XXXXXX[3] = letters[v % NLETTERS];
1290       v /= NLETTERS;
1291       XXXXXX[4] = letters[v % NLETTERS];
1292       v /= NLETTERS;
1293       XXXXXX[5] = letters[v % NLETTERS];
1294
1295       /* This is the backward compatibility system codepage version,
1296        * thus use normal open().
1297        */
1298       fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1299
1300       if (fd >= 0)
1301         return fd;
1302       else if (errno != EEXIST)
1303         /* Any other error will apply also to other names we might
1304          *  try, and there are 2^32 or so of them, so give up now.
1305          */
1306         return -1;
1307     }
1308
1309   /* We got out of the loop because we ran out of combinations to try.  */
1310   errno = EEXIST;
1311   return -1;
1312 }
1313
1314 #endif
1315
1316 /**
1317  * g_file_open_tmp:
1318  * @tmpl: Template for file name, as in g_mkstemp(), basename only
1319  * @name_used: location to store actual name used
1320  * @error: return location for a #GError
1321  *
1322  * Opens a file for writing in the preferred directory for temporary
1323  * files (as returned by g_get_tmp_dir()). 
1324  *
1325  * @tmpl should be a string in the GLib file name encoding ending with
1326  * six 'X' characters, as the parameter to g_mkstemp() (or mkstemp()).
1327  * However, unlike these functions, the template should only be a
1328  * basename, no directory components are allowed. If template is
1329  * %NULL, a default template is used.
1330  *
1331  * Note that in contrast to g_mkstemp() (and mkstemp()) 
1332  * @tmpl is not modified, and might thus be a read-only literal string.
1333  *
1334  * The actual name used is returned in @name_used if non-%NULL. This
1335  * string should be freed with g_free() when not needed any longer.
1336  * The returned name is in the GLib file name encoding.
1337  *
1338  * Return value: A file handle (as from open()) to 
1339  * the file opened for reading and writing. The file is opened in binary 
1340  * mode on platforms where there is a difference. The file handle should be
1341  * closed with close(). In case of errors, -1 is returned 
1342  * and @error will be set.
1343  **/
1344 gint
1345 g_file_open_tmp (const gchar *tmpl,
1346                  gchar      **name_used,
1347                  GError     **error)
1348 {
1349   int retval;
1350   const char *tmpdir;
1351   char *sep;
1352   char *fulltemplate;
1353   const char *slash;
1354
1355   if (tmpl == NULL)
1356     tmpl = ".XXXXXX";
1357
1358   if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1359 #ifdef G_OS_WIN32
1360       || (strchr (tmpl, '/') != NULL && (slash = "/"))
1361 #endif
1362       )
1363     {
1364       gchar *display_tmpl = g_filename_display_name (tmpl);
1365       char c[2];
1366       c[0] = *slash;
1367       c[1] = '\0';
1368
1369       g_set_error (error,
1370                    G_FILE_ERROR,
1371                    G_FILE_ERROR_FAILED,
1372                    _("Template '%s' invalid, should not contain a '%s'"),
1373                    display_tmpl, c);
1374       g_free (display_tmpl);
1375
1376       return -1;
1377     }
1378   
1379   if (strlen (tmpl) < 6 ||
1380       strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
1381     {
1382       gchar *display_tmpl = g_filename_display_name (tmpl);
1383       g_set_error (error,
1384                    G_FILE_ERROR,
1385                    G_FILE_ERROR_FAILED,
1386                    _("Template '%s' doesn't end with XXXXXX"),
1387                    display_tmpl);
1388       g_free (display_tmpl);
1389       return -1;
1390     }
1391
1392   tmpdir = g_get_tmp_dir ();
1393
1394   if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1395     sep = "";
1396   else
1397     sep = G_DIR_SEPARATOR_S;
1398
1399   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1400
1401   retval = g_mkstemp (fulltemplate);
1402
1403   if (retval == -1)
1404     {
1405       int save_errno = errno;
1406       gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1407
1408       g_set_error (error,
1409                    G_FILE_ERROR,
1410                    g_file_error_from_errno (save_errno),
1411                    _("Failed to create file '%s': %s"),
1412                    display_fulltemplate, g_strerror (save_errno));
1413       g_free (display_fulltemplate);
1414       g_free (fulltemplate);
1415       return -1;
1416     }
1417
1418   if (name_used)
1419     *name_used = fulltemplate;
1420   else
1421     g_free (fulltemplate);
1422
1423   return retval;
1424 }
1425
1426 #ifdef G_OS_WIN32
1427
1428 #undef g_file_open_tmp
1429
1430 /* Binary compatibility version. Not for newly compiled code. */
1431
1432 gint
1433 g_file_open_tmp (const gchar *tmpl,
1434                  gchar      **name_used,
1435                  GError     **error)
1436 {
1437   gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1438   gchar *utf8_name_used;
1439   gint retval;
1440
1441   if (utf8_tmpl == NULL)
1442     return -1;
1443
1444   retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1445   
1446   if (retval == -1)
1447     return -1;
1448
1449   if (name_used)
1450     *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1451
1452   g_free (utf8_name_used);
1453
1454   return retval;
1455 }
1456
1457 #endif
1458
1459 static gchar *
1460 g_build_path_va (const gchar  *separator,
1461                  const gchar  *first_element,
1462                  va_list      *args,
1463                  gchar       **str_array)
1464 {
1465   GString *result;
1466   gint separator_len = strlen (separator);
1467   gboolean is_first = TRUE;
1468   gboolean have_leading = FALSE;
1469   const gchar *single_element = NULL;
1470   const gchar *next_element;
1471   const gchar *last_trailing = NULL;
1472   gint i = 0;
1473
1474   result = g_string_new (NULL);
1475
1476   if (str_array)
1477     next_element = str_array[i++];
1478   else
1479     next_element = first_element;
1480
1481   while (TRUE)
1482     {
1483       const gchar *element;
1484       const gchar *start;
1485       const gchar *end;
1486
1487       if (next_element)
1488         {
1489           element = next_element;
1490           if (str_array)
1491             next_element = str_array[i++];
1492           else
1493             next_element = va_arg (*args, gchar *);
1494         }
1495       else
1496         break;
1497
1498       /* Ignore empty elements */
1499       if (!*element)
1500         continue;
1501       
1502       start = element;
1503
1504       if (separator_len)
1505         {
1506           while (start &&
1507                  strncmp (start, separator, separator_len) == 0)
1508             start += separator_len;
1509         }
1510
1511       end = start + strlen (start);
1512       
1513       if (separator_len)
1514         {
1515           while (end >= start + separator_len &&
1516                  strncmp (end - separator_len, separator, separator_len) == 0)
1517             end -= separator_len;
1518           
1519           last_trailing = end;
1520           while (last_trailing >= element + separator_len &&
1521                  strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1522             last_trailing -= separator_len;
1523
1524           if (!have_leading)
1525             {
1526               /* If the leading and trailing separator strings are in the
1527                * same element and overlap, the result is exactly that element
1528                */
1529               if (last_trailing <= start)
1530                 single_element = element;
1531                   
1532               g_string_append_len (result, element, start - element);
1533               have_leading = TRUE;
1534             }
1535           else
1536             single_element = NULL;
1537         }
1538
1539       if (end == start)
1540         continue;
1541
1542       if (!is_first)
1543         g_string_append (result, separator);
1544       
1545       g_string_append_len (result, start, end - start);
1546       is_first = FALSE;
1547     }
1548
1549   if (single_element)
1550     {
1551       g_string_free (result, TRUE);
1552       return g_strdup (single_element);
1553     }
1554   else
1555     {
1556       if (last_trailing)
1557         g_string_append (result, last_trailing);
1558   
1559       return g_string_free (result, FALSE);
1560     }
1561 }
1562
1563 /**
1564  * g_build_pathv:
1565  * @separator: a string used to separator the elements of the path.
1566  * @args: %NULL-terminated array of strings containing the path elements.
1567  * 
1568  * Behaves exactly like g_build_path(), but takes the path elements 
1569  * as a string array, instead of varargs. This function is mainly
1570  * meant for language bindings.
1571  *
1572  * Return value: a newly-allocated string that must be freed with g_free().
1573  *
1574  * Since: 2.8
1575  */
1576 gchar *
1577 g_build_pathv (const gchar  *separator,
1578                gchar       **args)
1579 {
1580   if (!args)
1581     return NULL;
1582
1583   return g_build_path_va (separator, NULL, NULL, args);
1584 }
1585
1586
1587 /**
1588  * g_build_path:
1589  * @separator: a string used to separator the elements of the path.
1590  * @first_element: the first element in the path
1591  * @Varargs: remaining elements in path, terminated by %NULL
1592  * 
1593  * Creates a path from a series of elements using @separator as the
1594  * separator between elements. At the boundary between two elements,
1595  * any trailing occurrences of separator in the first element, or
1596  * leading occurrences of separator in the second element are removed
1597  * and exactly one copy of the separator is inserted.
1598  *
1599  * Empty elements are ignored.
1600  *
1601  * The number of leading copies of the separator on the result is
1602  * the same as the number of leading copies of the separator on
1603  * the first non-empty element.
1604  *
1605  * The number of trailing copies of the separator on the result is
1606  * the same as the number of trailing copies of the separator on
1607  * the last non-empty element. (Determination of the number of
1608  * trailing copies is done without stripping leading copies, so
1609  * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1610  * has 1 trailing copy.)
1611  *
1612  * However, if there is only a single non-empty element, and there
1613  * are no characters in that element not part of the leading or
1614  * trailing separators, then the result is exactly the original value
1615  * of that element.
1616  *
1617  * Other than for determination of the number of leading and trailing
1618  * copies of the separator, elements consisting only of copies
1619  * of the separator are ignored.
1620  * 
1621  * Return value: a newly-allocated string that must be freed with g_free().
1622  **/
1623 gchar *
1624 g_build_path (const gchar *separator,
1625               const gchar *first_element,
1626               ...)
1627 {
1628   gchar *str;
1629   va_list args;
1630
1631   g_return_val_if_fail (separator != NULL, NULL);
1632
1633   va_start (args, first_element);
1634   str = g_build_path_va (separator, first_element, &args, NULL);
1635   va_end (args);
1636
1637   return str;
1638 }
1639
1640 #ifdef G_OS_WIN32
1641
1642 static gchar *
1643 g_build_pathname_va (const gchar  *first_element,
1644                      va_list      *args,
1645                      gchar       **str_array)
1646 {
1647   /* Code copied from g_build_pathv(), and modified to use two
1648    * alternative single-character separators.
1649    */
1650   GString *result;
1651   gboolean is_first = TRUE;
1652   gboolean have_leading = FALSE;
1653   const gchar *single_element = NULL;
1654   const gchar *next_element;
1655   const gchar *last_trailing = NULL;
1656   gchar current_separator = '\\';
1657   gint i = 0;
1658
1659   result = g_string_new (NULL);
1660
1661   if (str_array)
1662     next_element = str_array[i++];
1663   else
1664     next_element = first_element;
1665   
1666   while (TRUE)
1667     {
1668       const gchar *element;
1669       const gchar *start;
1670       const gchar *end;
1671
1672       if (next_element)
1673         {
1674           element = next_element;
1675           if (str_array)
1676             next_element = str_array[i++];
1677           else
1678             next_element = va_arg (*args, gchar *);
1679         }
1680       else
1681         break;
1682
1683       /* Ignore empty elements */
1684       if (!*element)
1685         continue;
1686       
1687       start = element;
1688
1689       if (TRUE)
1690         {
1691           while (start &&
1692                  (*start == '\\' || *start == '/'))
1693             {
1694               current_separator = *start;
1695               start++;
1696             }
1697         }
1698
1699       end = start + strlen (start);
1700       
1701       if (TRUE)
1702         {
1703           while (end >= start + 1 &&
1704                  (end[-1] == '\\' || end[-1] == '/'))
1705             {
1706               current_separator = end[-1];
1707               end--;
1708             }
1709           
1710           last_trailing = end;
1711           while (last_trailing >= element + 1 &&
1712                  (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1713             last_trailing--;
1714
1715           if (!have_leading)
1716             {
1717               /* If the leading and trailing separator strings are in the
1718                * same element and overlap, the result is exactly that element
1719                */
1720               if (last_trailing <= start)
1721                 single_element = element;
1722                   
1723               g_string_append_len (result, element, start - element);
1724               have_leading = TRUE;
1725             }
1726           else
1727             single_element = NULL;
1728         }
1729
1730       if (end == start)
1731         continue;
1732
1733       if (!is_first)
1734         g_string_append_len (result, &current_separator, 1);
1735       
1736       g_string_append_len (result, start, end - start);
1737       is_first = FALSE;
1738     }
1739
1740   if (single_element)
1741     {
1742       g_string_free (result, TRUE);
1743       return g_strdup (single_element);
1744     }
1745   else
1746     {
1747       if (last_trailing)
1748         g_string_append (result, last_trailing);
1749   
1750       return g_string_free (result, FALSE);
1751     }
1752 }
1753
1754 #endif
1755
1756 /**
1757  * g_build_filenamev:
1758  * @args: %NULL-terminated array of strings containing the path elements.
1759  * 
1760  * Behaves exactly like g_build_filename(), but takes the path elements 
1761  * as a string array, instead of varargs. This function is mainly
1762  * meant for language bindings.
1763  *
1764  * Return value: a newly-allocated string that must be freed with g_free().
1765  * 
1766  * Since: 2.8
1767  */
1768 gchar *
1769 g_build_filenamev (gchar **args)
1770 {
1771   gchar *str;
1772
1773 #ifndef G_OS_WIN32
1774   str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1775 #else
1776   str = g_build_pathname_va (NULL, NULL, args);
1777 #endif
1778
1779   return str;
1780 }
1781
1782 /**
1783  * g_build_filename:
1784  * @first_element: the first element in the path
1785  * @Varargs: remaining elements in path, terminated by %NULL
1786  * 
1787  * Creates a filename from a series of elements using the correct
1788  * separator for filenames.
1789  *
1790  * On Unix, this function behaves identically to <literal>g_build_path
1791  * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1792  *
1793  * On Windows, it takes into account that either the backslash
1794  * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1795  * as separator in filenames, but otherwise behaves as on Unix. When
1796  * file pathname separators need to be inserted, the one that last
1797  * previously occurred in the parameters (reading from left to right)
1798  * is used.
1799  *
1800  * No attempt is made to force the resulting filename to be an absolute
1801  * path. If the first element is a relative path, the result will
1802  * be a relative path. 
1803  * 
1804  * Return value: a newly-allocated string that must be freed with g_free().
1805  **/
1806 gchar *
1807 g_build_filename (const gchar *first_element, 
1808                   ...)
1809 {
1810   gchar *str;
1811   va_list args;
1812
1813   va_start (args, first_element);
1814 #ifndef G_OS_WIN32
1815   str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1816 #else
1817   str = g_build_pathname_va (first_element, &args, NULL);
1818 #endif
1819   va_end (args);
1820
1821   return str;
1822 }
1823
1824 /**
1825  * g_file_read_link:
1826  * @filename: the symbolic link
1827  * @error: return location for a #GError
1828  *
1829  * Reads the contents of the symbolic link @filename like the POSIX
1830  * readlink() function.  The returned string is in the encoding used
1831  * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1832  *
1833  * Returns: A newly allocated string with the contents of the symbolic link, 
1834  *          or %NULL if an error occurred.
1835  *
1836  * Since: 2.4
1837  */
1838 gchar *
1839 g_file_read_link (const gchar *filename,
1840                   GError     **error)
1841 {
1842 #ifdef HAVE_READLINK
1843   gchar *buffer;
1844   guint size;
1845   gint read_size;    
1846   
1847   size = 256; 
1848   buffer = g_malloc (size);
1849   
1850   while (TRUE) 
1851     {
1852       read_size = readlink (filename, buffer, size);
1853       if (read_size < 0) {
1854         int save_errno = errno;
1855         gchar *display_filename = g_filename_display_name (filename);
1856
1857         g_free (buffer);
1858         g_set_error (error,
1859                      G_FILE_ERROR,
1860                      g_file_error_from_errno (save_errno),
1861                      _("Failed to read the symbolic link '%s': %s"),
1862                      display_filename, 
1863                      g_strerror (save_errno));
1864         g_free (display_filename);
1865         
1866         return NULL;
1867       }
1868     
1869       if (read_size < size) 
1870         {
1871           buffer[read_size] = 0;
1872           return buffer;
1873         }
1874       
1875       size *= 2;
1876       buffer = g_realloc (buffer, size);
1877     }
1878 #else
1879   g_set_error (error,
1880                G_FILE_ERROR,
1881                G_FILE_ERROR_INVAL,
1882                _("Symbolic links not supported"));
1883         
1884   return NULL;
1885 #endif
1886 }
1887
1888 #define __G_FILEUTILS_C__
1889 #include "galiasdef.c"