Fix some C99isms. (#154676, Kjartan Maraas)
[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 "galias.h"
24 #include "glib.h"
25
26 #include <sys/stat.h>
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <string.h>
34 #include <errno.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <fcntl.h>
38 #include <stdlib.h>
39
40 #ifdef G_OS_WIN32
41 #include <io.h>
42 #ifndef F_OK
43 #define F_OK 0
44 #define W_OK 2
45 #define R_OK 4
46 #endif /* !F_OK */
47
48 #ifndef S_ISREG
49 #define S_ISREG(mode) ((mode)&_S_IFREG)
50 #endif
51
52 #ifndef S_ISDIR
53 #define S_ISDIR(mode) ((mode)&_S_IFDIR)
54 #endif
55
56 #endif /* G_OS_WIN32 */
57
58 #ifndef S_ISLNK
59 #define S_ISLNK(x) 0
60 #endif
61
62 #ifndef O_BINARY
63 #define O_BINARY 0
64 #endif
65
66 #include "glibintl.h"
67
68 #ifdef G_OS_WIN32
69 #define G_IS_DIR_SEPARATOR(c) (c == G_DIR_SEPARATOR || c == '/')
70 #else
71 #define G_IS_DIR_SEPARATOR(c) (c == G_DIR_SEPARATOR)
72 #endif
73
74 /**
75  * g_file_test:
76  * @filename: a filename to test
77  * @test: bitfield of #GFileTest flags
78  * 
79  * Returns %TRUE if any of the tests in the bitfield @test are
80  * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS | 
81  * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists; 
82  * the check whether it's a directory doesn't matter since the existence 
83  * test is %TRUE. With the current set of available tests, there's no point
84  * passing in more than one test at a time.
85  * 
86  * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
87  * so for a symbolic link to a regular file g_file_test() will return
88  * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
89  *
90  * Note, that for a dangling symbolic link g_file_test() will return
91  * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
92  *
93  * You should never use g_file_test() to test whether it is safe
94  * to perform an operaton, because there is always the possibility
95  * of the condition changing before you actually perform the operation.
96  * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
97  * to know whether it is is safe to write to a file without being
98  * tricked into writing into a different location. It doesn't work!
99  *
100  * <informalexample><programlisting>
101  * /&ast; DON'T DO THIS &ast;/
102  *  if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) {
103  *    fd = open (filename, O_WRONLY);
104  *    /&ast; write to fd &ast;/
105  *  }
106  * </programlisting></informalexample>
107  *
108  * Another thing to note is that %G_FILE_TEST_EXISTS and
109  * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
110  * system call. This usually doesn't matter, but if your program
111  * is setuid or setgid it means that these tests will give you
112  * the answer for the real user ID and group ID , rather than the
113  * effective user ID and group ID.
114  *
115  * Return value: whether a test was %TRUE
116  **/
117 gboolean
118 g_file_test (const gchar *filename,
119              GFileTest    test)
120 {
121   if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
122     return TRUE;
123   
124 #ifndef G_OS_WIN32
125   if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
126     {
127       if (getuid () != 0)
128         return TRUE;
129
130       /* For root, on some POSIX systems, access (filename, X_OK)
131        * will succeed even if no executable bits are set on the
132        * file. We fall through to a stat test to avoid that.
133        */
134     }
135   else
136     test &= ~G_FILE_TEST_IS_EXECUTABLE;
137 #endif  
138
139   if (test & G_FILE_TEST_IS_SYMLINK)
140     {
141 #ifdef G_OS_WIN32
142       /* no sym links on win32, no lstat in msvcrt */
143 #else
144       struct stat s;
145
146       if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
147         return TRUE;
148 #endif
149     }
150   
151   if (test & (G_FILE_TEST_IS_REGULAR |
152               G_FILE_TEST_IS_DIR |
153               G_FILE_TEST_IS_EXECUTABLE))
154     {
155       struct stat s;
156       
157       if (stat (filename, &s) == 0)
158         {
159           if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
160             return TRUE;
161           
162           if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
163             return TRUE;
164
165 #ifndef G_OS_WIN32
166           /* The extra test for root when access (file, X_OK) succeeds.
167            * Probably only makes sense on Unix.
168            */
169           if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
170               ((s.st_mode & S_IXOTH) ||
171                (s.st_mode & S_IXUSR) ||
172                (s.st_mode & S_IXGRP)))
173             return TRUE;
174 #else
175           if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
176               (s.st_mode & _S_IEXEC))
177             return TRUE;
178 #endif
179         }
180     }
181
182   return FALSE;
183 }
184
185 GQuark
186 g_file_error_quark (void)
187 {
188   static GQuark q = 0;
189   if (q == 0)
190     q = g_quark_from_static_string ("g-file-error-quark");
191
192   return q;
193 }
194
195 /**
196  * g_file_error_from_errno:
197  * @err_no: an "errno" value
198  * 
199  * Gets a #GFileError constant based on the passed-in @errno.
200  * For example, if you pass in %EEXIST this function returns
201  * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
202  * assume that all #GFileError values will exist.
203  *
204  * Normally a #GFileError value goes into a #GError returned
205  * from a function that manipulates files. So you would use
206  * g_file_error_from_errno() when constructing a #GError.
207  * 
208  * Return value: #GFileError corresponding to the given @errno
209  **/
210 GFileError
211 g_file_error_from_errno (gint err_no)
212 {
213   switch (err_no)
214     {
215 #ifdef EEXIST
216     case EEXIST:
217       return G_FILE_ERROR_EXIST;
218       break;
219 #endif
220
221 #ifdef EISDIR
222     case EISDIR:
223       return G_FILE_ERROR_ISDIR;
224       break;
225 #endif
226
227 #ifdef EACCES
228     case EACCES:
229       return G_FILE_ERROR_ACCES;
230       break;
231 #endif
232
233 #ifdef ENAMETOOLONG
234     case ENAMETOOLONG:
235       return G_FILE_ERROR_NAMETOOLONG;
236       break;
237 #endif
238
239 #ifdef ENOENT
240     case ENOENT:
241       return G_FILE_ERROR_NOENT;
242       break;
243 #endif
244
245 #ifdef ENOTDIR
246     case ENOTDIR:
247       return G_FILE_ERROR_NOTDIR;
248       break;
249 #endif
250
251 #ifdef ENXIO
252     case ENXIO:
253       return G_FILE_ERROR_NXIO;
254       break;
255 #endif
256
257 #ifdef ENODEV
258     case ENODEV:
259       return G_FILE_ERROR_NODEV;
260       break;
261 #endif
262
263 #ifdef EROFS
264     case EROFS:
265       return G_FILE_ERROR_ROFS;
266       break;
267 #endif
268
269 #ifdef ETXTBSY
270     case ETXTBSY:
271       return G_FILE_ERROR_TXTBSY;
272       break;
273 #endif
274
275 #ifdef EFAULT
276     case EFAULT:
277       return G_FILE_ERROR_FAULT;
278       break;
279 #endif
280
281 #ifdef ELOOP
282     case ELOOP:
283       return G_FILE_ERROR_LOOP;
284       break;
285 #endif
286
287 #ifdef ENOSPC
288     case ENOSPC:
289       return G_FILE_ERROR_NOSPC;
290       break;
291 #endif
292
293 #ifdef ENOMEM
294     case ENOMEM:
295       return G_FILE_ERROR_NOMEM;
296       break;
297 #endif
298
299 #ifdef EMFILE
300     case EMFILE:
301       return G_FILE_ERROR_MFILE;
302       break;
303 #endif
304
305 #ifdef ENFILE
306     case ENFILE:
307       return G_FILE_ERROR_NFILE;
308       break;
309 #endif
310
311 #ifdef EBADF
312     case EBADF:
313       return G_FILE_ERROR_BADF;
314       break;
315 #endif
316
317 #ifdef EINVAL
318     case EINVAL:
319       return G_FILE_ERROR_INVAL;
320       break;
321 #endif
322
323 #ifdef EPIPE
324     case EPIPE:
325       return G_FILE_ERROR_PIPE;
326       break;
327 #endif
328
329 #ifdef EAGAIN
330     case EAGAIN:
331       return G_FILE_ERROR_AGAIN;
332       break;
333 #endif
334
335 #ifdef EINTR
336     case EINTR:
337       return G_FILE_ERROR_INTR;
338       break;
339 #endif
340
341 #ifdef EIO
342     case EIO:
343       return G_FILE_ERROR_IO;
344       break;
345 #endif
346
347 #ifdef EPERM
348     case EPERM:
349       return G_FILE_ERROR_PERM;
350       break;
351 #endif
352
353 #ifdef ENOSYS
354     case ENOSYS:
355       return G_FILE_ERROR_NOSYS;
356       break;
357 #endif
358
359     default:
360       return G_FILE_ERROR_FAILED;
361       break;
362     }
363 }
364
365 static gboolean
366 get_contents_stdio (const gchar *filename,
367                     FILE        *f,
368                     gchar      **contents,
369                     gsize       *length, 
370                     GError     **error)
371 {
372   gchar buf[2048];
373   size_t bytes;
374   char *str;
375   size_t total_bytes;
376   size_t total_allocated;
377   
378   g_assert (f != NULL);
379
380 #define STARTING_ALLOC 64
381   
382   total_bytes = 0;
383   total_allocated = STARTING_ALLOC;
384   str = g_malloc (STARTING_ALLOC);
385   
386   while (!feof (f))
387     {
388       bytes = fread (buf, 1, 2048, f);
389
390       while ((total_bytes + bytes + 1) > total_allocated)
391         {
392           total_allocated *= 2;
393           str = g_try_realloc (str, total_allocated);
394
395           if (str == NULL)
396             {
397               gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
398                                                          NULL, NULL, NULL);
399               g_set_error (error,
400                            G_FILE_ERROR,
401                            G_FILE_ERROR_NOMEM,
402                            _("Could not allocate %lu bytes to read file \"%s\""),
403                            (gulong) total_allocated, 
404                            utf8_filename ? utf8_filename : "???");
405               g_free (utf8_filename);
406
407               goto error;
408             }
409         }
410       
411       if (ferror (f))
412         {
413           gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
414                                                      NULL, NULL, NULL);
415           g_set_error (error,
416                        G_FILE_ERROR,
417                        g_file_error_from_errno (errno),
418                        _("Error reading file '%s': %s"),
419                        utf8_filename ? utf8_filename : "???", 
420                        g_strerror (errno));
421           g_free (utf8_filename);
422
423           goto error;
424         }
425
426       memcpy (str + total_bytes, buf, bytes);
427       total_bytes += bytes;
428     }
429
430   fclose (f);
431
432   str[total_bytes] = '\0';
433   
434   if (length)
435     *length = total_bytes;
436   
437   *contents = str;
438   
439   return TRUE;
440
441  error:
442
443   g_free (str);
444   fclose (f);
445   
446   return FALSE;  
447 }
448
449 #ifndef G_OS_WIN32
450
451 static gboolean
452 get_contents_regfile (const gchar *filename,
453                       struct stat *stat_buf,
454                       gint         fd,
455                       gchar      **contents,
456                       gsize       *length,
457                       GError     **error)
458 {
459   gchar *buf;
460   size_t bytes_read;
461   size_t size;
462   size_t alloc_size;
463   
464   size = stat_buf->st_size;
465
466   alloc_size = size + 1;
467   buf = g_try_malloc (alloc_size);
468
469   if (buf == NULL)
470     {
471       gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
472                                                  NULL, NULL, NULL);
473       g_set_error (error,
474                    G_FILE_ERROR,
475                    G_FILE_ERROR_NOMEM,
476                    _("Could not allocate %lu bytes to read file \"%s\""),
477                    (gulong) alloc_size, 
478                    utf8_filename ? utf8_filename : "???");
479       g_free (utf8_filename);
480
481       goto error;
482     }
483   
484   bytes_read = 0;
485   while (bytes_read < size)
486     {
487       gssize rc;
488           
489       rc = read (fd, buf + bytes_read, size - bytes_read);
490
491       if (rc < 0)
492         {
493           if (errno != EINTR) 
494             {
495               gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
496                                                          NULL, NULL, NULL);
497               g_free (buf);
498               g_set_error (error,
499                            G_FILE_ERROR,
500                            g_file_error_from_errno (errno),
501                            _("Failed to read from file '%s': %s"),
502                            utf8_filename ? utf8_filename : "???", 
503                            g_strerror (errno));
504               g_free (utf8_filename);
505
506               goto error;
507             }
508         }
509       else if (rc == 0)
510         break;
511       else
512         bytes_read += rc;
513     }
514       
515   buf[bytes_read] = '\0';
516
517   if (length)
518     *length = bytes_read;
519   
520   *contents = buf;
521
522   close (fd);
523
524   return TRUE;
525
526  error:
527
528   close (fd);
529   
530   return FALSE;
531 }
532
533 static gboolean
534 get_contents_posix (const gchar *filename,
535                     gchar      **contents,
536                     gsize       *length,
537                     GError     **error)
538 {
539   struct stat stat_buf;
540   gint fd;
541   
542   /* O_BINARY useful on Cygwin */
543   fd = open (filename, O_RDONLY|O_BINARY);
544
545   if (fd < 0)
546     {
547       gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
548                                                  NULL, NULL, NULL);
549       g_set_error (error,
550                    G_FILE_ERROR,
551                    g_file_error_from_errno (errno),
552                    _("Failed to open file '%s': %s"),
553                    utf8_filename ? utf8_filename : "???", 
554                    g_strerror (errno));
555       g_free (utf8_filename);
556
557       return FALSE;
558     }
559
560   /* I don't think this will ever fail, aside from ENOMEM, but. */
561   if (fstat (fd, &stat_buf) < 0)
562     {
563       gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
564                                                  NULL, NULL, NULL);
565       close (fd);
566       g_set_error (error,
567                    G_FILE_ERROR,
568                    g_file_error_from_errno (errno),
569                    _("Failed to get attributes of file '%s': fstat() failed: %s"),
570                    utf8_filename ? utf8_filename : "???", 
571                    g_strerror (errno));
572       g_free (utf8_filename);
573
574       return FALSE;
575     }
576
577   if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
578     {
579       return get_contents_regfile (filename,
580                                    &stat_buf,
581                                    fd,
582                                    contents,
583                                    length,
584                                    error);
585     }
586   else
587     {
588       FILE *f;
589
590       f = fdopen (fd, "r");
591       
592       if (f == NULL)
593         {
594           gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
595                                                      NULL, NULL, NULL);
596
597           g_set_error (error,
598                        G_FILE_ERROR,
599                        g_file_error_from_errno (errno),
600                        _("Failed to open file '%s': fdopen() failed: %s"),
601                        utf8_filename ? utf8_filename : "???", 
602                        g_strerror (errno));
603           g_free (utf8_filename);
604
605           return FALSE;
606         }
607   
608       return get_contents_stdio (filename, f, contents, length, error);
609     }
610 }
611
612 #else  /* G_OS_WIN32 */
613
614 static gboolean
615 get_contents_win32 (const gchar *filename,
616                     gchar      **contents,
617                     gsize       *length,
618                     GError     **error)
619 {
620   FILE *f;
621
622   /* I guess you want binary mode; maybe you want text sometimes? */
623   f = fopen (filename, "rb");
624
625   if (f == NULL)
626     {
627       gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
628                                                  NULL, NULL, NULL);
629       
630       g_set_error (error,
631                    G_FILE_ERROR,
632                    g_file_error_from_errno (errno),
633                    _("Failed to open file '%s': %s"),
634                    utf8_filename ? utf8_filename : "???", 
635                    g_strerror (errno));
636       g_free (utf8_filename);
637
638       return FALSE;
639     }
640   
641   return get_contents_stdio (filename, f, contents, length, error);
642 }
643
644 #endif
645
646 /**
647  * g_file_get_contents:
648  * @filename: a file to read contents from
649  * @contents: location to store an allocated string
650  * @length: location to store length in bytes of the contents
651  * @error: return location for a #GError
652  * 
653  * Reads an entire file into allocated memory, with good error
654  * checking. If @error is set, %FALSE is returned, and @contents is set
655  * to %NULL. If %TRUE is returned, @error will not be set, and @contents
656  * will be set to the file contents.  The string stored in @contents
657  * will be nul-terminated, so for text files you can pass %NULL for the
658  * @length argument.  The error domain is #G_FILE_ERROR. Possible
659  * error codes are those in the #GFileError enumeration.
660  *
661  * Return value: %TRUE on success, %FALSE if error is set
662  **/
663 gboolean
664 g_file_get_contents (const gchar *filename,
665                      gchar      **contents,
666                      gsize       *length,
667                      GError     **error)
668 {  
669   g_return_val_if_fail (filename != NULL, FALSE);
670   g_return_val_if_fail (contents != NULL, FALSE);
671
672   *contents = NULL;
673   if (length)
674     *length = 0;
675
676 #ifdef G_OS_WIN32
677   return get_contents_win32 (filename, contents, length, error);
678 #else
679   return get_contents_posix (filename, contents, length, error);
680 #endif
681 }
682
683 /*
684  * mkstemp() implementation is from the GNU C library.
685  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
686  */
687 /**
688  * g_mkstemp:
689  * @tmpl: template filename
690  *
691  * Opens a temporary file. See the mkstemp() documentation
692  * on most UNIX-like systems. This is a portability wrapper, which simply calls 
693  * mkstemp() on systems that have it, and implements 
694  * it in GLib otherwise.
695  *
696  * The parameter is a string that should match the rules for
697  * mkstemp(), i.e. end in "XXXXXX". The X string will 
698  * be modified to form the name of a file that didn't exist.
699  *
700  * Return value: A file handle (as from open()) to the file
701  * opened for reading and writing. The file is opened in binary mode
702  * on platforms where there is a difference. The file handle should be
703  * closed with close(). In case of errors, -1 is returned.
704  */
705 gint
706 g_mkstemp (gchar *tmpl)
707 {
708 #ifdef HAVE_MKSTEMP
709   return mkstemp (tmpl);
710 #else
711   int len;
712   char *XXXXXX;
713   int count, fd;
714   static const char letters[] =
715     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
716   static const int NLETTERS = sizeof (letters) - 1;
717   glong value;
718   GTimeVal tv;
719   static int counter = 0;
720
721   len = strlen (tmpl);
722   if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
723     return -1;
724
725   /* This is where the Xs start.  */
726   XXXXXX = &tmpl[len - 6];
727
728   /* Get some more or less random data.  */
729   g_get_current_time (&tv);
730   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
731
732   for (count = 0; count < 100; value += 7777, ++count)
733     {
734       glong v = value;
735
736       /* Fill in the random bits.  */
737       XXXXXX[0] = letters[v % NLETTERS];
738       v /= NLETTERS;
739       XXXXXX[1] = letters[v % NLETTERS];
740       v /= NLETTERS;
741       XXXXXX[2] = letters[v % NLETTERS];
742       v /= NLETTERS;
743       XXXXXX[3] = letters[v % NLETTERS];
744       v /= NLETTERS;
745       XXXXXX[4] = letters[v % NLETTERS];
746       v /= NLETTERS;
747       XXXXXX[5] = letters[v % NLETTERS];
748
749       fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
750
751       if (fd >= 0)
752         return fd;
753       else if (errno != EEXIST)
754         /* Any other error will apply also to other names we might
755          *  try, and there are 2^32 or so of them, so give up now.
756          */
757         return -1;
758     }
759
760   /* We got out of the loop because we ran out of combinations to try.  */
761   return -1;
762 #endif
763 }
764
765 /**
766  * g_file_open_tmp:
767  * @tmpl: Template for file name, as in g_mkstemp(), basename only
768  * @name_used: location to store actual name used
769  * @error: return location for a #GError
770  *
771  * Opens a file for writing in the preferred directory for temporary
772  * files (as returned by g_get_tmp_dir()). 
773  *
774  * @tmpl should be a string ending with six 'X' characters, as the
775  * parameter to g_mkstemp() (or mkstemp()). 
776  * However, unlike these functions, the template should only be a 
777  * basename, no directory components are allowed. If template is %NULL, 
778  * a default template is used.
779  *
780  * Note that in contrast to g_mkstemp() (and mkstemp()) 
781  * @tmpl is not modified, and might thus be a read-only literal string.
782  *
783  * The actual name used is returned in @name_used if non-%NULL. This
784  * string should be freed with g_free() when not needed any longer.
785  *
786  * Return value: A file handle (as from open()) to 
787  * the file opened for reading and writing. The file is opened in binary 
788  * mode on platforms where there is a difference. The file handle should be
789  * closed with close(). In case of errors, -1 is returned 
790  * and @error will be set.
791  **/
792 gint
793 g_file_open_tmp (const gchar *tmpl,
794                  gchar      **name_used,
795                  GError     **error)
796 {
797   int retval;
798   const char *tmpdir;
799   char *sep;
800   char *fulltemplate;
801   const char *slash;
802
803   if (tmpl == NULL)
804     tmpl = ".XXXXXX";
805
806   if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
807 #ifdef G_OS_WIN32
808       || (strchr (tmpl, '/') != NULL && (slash = "/"))
809 #endif
810       )
811     {
812       char c[2];
813       c[0] = *slash;
814       c[1] = '\0';
815
816       g_set_error (error,
817                    G_FILE_ERROR,
818                    G_FILE_ERROR_FAILED,
819                    _("Template '%s' invalid, should not contain a '%s'"),
820                    tmpl, c);
821
822       return -1;
823     }
824   
825   if (strlen (tmpl) < 6 ||
826       strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
827     {
828       g_set_error (error,
829                    G_FILE_ERROR,
830                    G_FILE_ERROR_FAILED,
831                    _("Template '%s' doesn't end with XXXXXX"),
832                    tmpl);
833       return -1;
834     }
835
836   tmpdir = g_get_tmp_dir ();
837
838   if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
839     sep = "";
840   else
841     sep = G_DIR_SEPARATOR_S;
842
843   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
844
845   retval = g_mkstemp (fulltemplate);
846
847   if (retval == -1)
848     {
849       g_set_error (error,
850                    G_FILE_ERROR,
851                    g_file_error_from_errno (errno),
852                    _("Failed to create file '%s': %s"),
853                    fulltemplate, g_strerror (errno));
854       g_free (fulltemplate);
855       return -1;
856     }
857
858   if (name_used)
859     *name_used = fulltemplate;
860   else
861     g_free (fulltemplate);
862
863   return retval;
864 }
865
866 static gchar *
867 g_build_pathv (const gchar *separator,
868                const gchar *first_element,
869                va_list      args)
870 {
871   GString *result;
872   gint separator_len = strlen (separator);
873   gboolean is_first = TRUE;
874   gboolean have_leading = FALSE;
875   const gchar *single_element = NULL;
876   const gchar *next_element;
877   const gchar *last_trailing = NULL;
878
879   result = g_string_new (NULL);
880
881   next_element = first_element;
882
883   while (TRUE)
884     {
885       const gchar *element;
886       const gchar *start;
887       const gchar *end;
888
889       if (next_element)
890         {
891           element = next_element;
892           next_element = va_arg (args, gchar *);
893         }
894       else
895         break;
896
897       /* Ignore empty elements */
898       if (!*element)
899         continue;
900       
901       start = element;
902
903       if (separator_len)
904         {
905           while (start &&
906                  strncmp (start, separator, separator_len) == 0)
907             start += separator_len;
908         }
909
910       end = start + strlen (start);
911       
912       if (separator_len)
913         {
914           while (end >= start + separator_len &&
915                  strncmp (end - separator_len, separator, separator_len) == 0)
916             end -= separator_len;
917           
918           last_trailing = end;
919           while (last_trailing >= element + separator_len &&
920                  strncmp (last_trailing - separator_len, separator, separator_len) == 0)
921             last_trailing -= separator_len;
922
923           if (!have_leading)
924             {
925               /* If the leading and trailing separator strings are in the
926                * same element and overlap, the result is exactly that element
927                */
928               if (last_trailing <= start)
929                 single_element = element;
930                   
931               g_string_append_len (result, element, start - element);
932               have_leading = TRUE;
933             }
934           else
935             single_element = NULL;
936         }
937
938       if (end == start)
939         continue;
940
941       if (!is_first)
942         g_string_append (result, separator);
943       
944       g_string_append_len (result, start, end - start);
945       is_first = FALSE;
946     }
947
948   if (single_element)
949     {
950       g_string_free (result, TRUE);
951       return g_strdup (single_element);
952     }
953   else
954     {
955       if (last_trailing)
956         g_string_append (result, last_trailing);
957   
958       return g_string_free (result, FALSE);
959     }
960 }
961
962 /**
963  * g_build_path:
964  * @separator: a string used to separator the elements of the path.
965  * @first_element: the first element in the path
966  * @Varargs: remaining elements in path, terminated by %NULL
967  * 
968  * Creates a path from a series of elements using @separator as the
969  * separator between elements. At the boundary between two elements,
970  * any trailing occurrences of separator in the first element, or
971  * leading occurrences of separator in the second element are removed
972  * and exactly one copy of the separator is inserted.
973  *
974  * Empty elements are ignored.
975  *
976  * The number of leading copies of the separator on the result is
977  * the same as the number of leading copies of the separator on
978  * the first non-empty element.
979  *
980  * The number of trailing copies of the separator on the result is
981  * the same as the number of trailing copies of the separator on
982  * the last non-empty element. (Determination of the number of
983  * trailing copies is done without stripping leading copies, so
984  * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
985  * has 1 trailing copy.)
986  *
987  * However, if there is only a single non-empty element, and there
988  * are no characters in that element not part of the leading or
989  * trailing separators, then the result is exactly the original value
990  * of that element.
991  *
992  * Other than for determination of the number of leading and trailing
993  * copies of the separator, elements consisting only of copies
994  * of the separator are ignored.
995  * 
996  * Return value: a newly-allocated string that must be freed with g_free().
997  **/
998 gchar *
999 g_build_path (const gchar *separator,
1000               const gchar *first_element,
1001               ...)
1002 {
1003   gchar *str;
1004   va_list args;
1005
1006   g_return_val_if_fail (separator != NULL, NULL);
1007
1008   va_start (args, first_element);
1009   str = g_build_pathv (separator, first_element, args);
1010   va_end (args);
1011
1012   return str;
1013 }
1014
1015 /**
1016  * g_build_filename:
1017  * @first_element: the first element in the path
1018  * @Varargs: remaining elements in path, terminated by %NULL
1019  * 
1020  * Creates a filename from a series of elements using the correct
1021  * separator for filenames.
1022  *
1023  * On Unix, this function behaves identically to <literal>g_build_path
1024  * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1025  *
1026  * On Windows, it takes into account that either the backslash
1027  * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1028  * as separator in filenames, but otherwise behaves as on Unix. When
1029  * file pathname separators need to be inserted, the one that last
1030  * previously occurred in the parameters (reading from left to right)
1031  * is used.
1032  *
1033  * No attempt is made to force the resulting filename to be an absolute
1034  * path. If the first element is a relative path, the result will
1035  * be a relative path. 
1036  * 
1037  * Return value: a newly-allocated string that must be freed with g_free().
1038  **/
1039 gchar *
1040 g_build_filename (const gchar *first_element, 
1041                   ...)
1042 {
1043 #ifndef G_OS_WIN32
1044   gchar *str;
1045   va_list args;
1046
1047   va_start (args, first_element);
1048   str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
1049   va_end (args);
1050
1051   return str;
1052 #else
1053   /* Code copied from g_build_pathv(), and modifed to use two
1054    * alternative single-character separators.
1055    */
1056   va_list args;
1057   GString *result;
1058   gboolean is_first = TRUE;
1059   gboolean have_leading = FALSE;
1060   const gchar *single_element = NULL;
1061   const gchar *next_element;
1062   const gchar *last_trailing = NULL;
1063   gchar current_separator = '\\';
1064
1065   va_start (args, first_element);
1066
1067   result = g_string_new (NULL);
1068
1069   next_element = first_element;
1070
1071   while (TRUE)
1072     {
1073       const gchar *element;
1074       const gchar *start;
1075       const gchar *end;
1076
1077       if (next_element)
1078         {
1079           element = next_element;
1080           next_element = va_arg (args, gchar *);
1081         }
1082       else
1083         break;
1084
1085       /* Ignore empty elements */
1086       if (!*element)
1087         continue;
1088       
1089       start = element;
1090
1091       if (TRUE)
1092         {
1093           while (start &&
1094                  (*start == '\\' || *start == '/'))
1095             {
1096               current_separator = *start;
1097               start++;
1098             }
1099         }
1100
1101       end = start + strlen (start);
1102       
1103       if (TRUE)
1104         {
1105           while (end >= start + 1 &&
1106                  (end[-1] == '\\' || end[-1] == '/'))
1107             {
1108               current_separator = end[-1];
1109               end--;
1110             }
1111           
1112           last_trailing = end;
1113           while (last_trailing >= element + 1 &&
1114                  (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1115             last_trailing--;
1116
1117           if (!have_leading)
1118             {
1119               /* If the leading and trailing separator strings are in the
1120                * same element and overlap, the result is exactly that element
1121                */
1122               if (last_trailing <= start)
1123                 single_element = element;
1124                   
1125               g_string_append_len (result, element, start - element);
1126               have_leading = TRUE;
1127             }
1128           else
1129             single_element = NULL;
1130         }
1131
1132       if (end == start)
1133         continue;
1134
1135       if (!is_first)
1136         g_string_append_len (result, &current_separator, 1);
1137       
1138       g_string_append_len (result, start, end - start);
1139       is_first = FALSE;
1140     }
1141
1142   va_end (args);
1143
1144   if (single_element)
1145     {
1146       g_string_free (result, TRUE);
1147       return g_strdup (single_element);
1148     }
1149   else
1150     {
1151       if (last_trailing)
1152         g_string_append (result, last_trailing);
1153   
1154       return g_string_free (result, FALSE);
1155     }
1156 #endif
1157 }
1158
1159 /**
1160  * g_file_read_link:
1161  * @filename: the symbolic link
1162  * @error: return location for a #GError
1163  *
1164  * Reads the contents of the symbolic link @filename like the POSIX readlink() function.
1165  * The returned string is in the encoding used for filenames. Use g_filename_to_utf8() to 
1166  * convert it to UTF-8.
1167  *
1168  * Returns: A newly allocated string with the contents of the symbolic link, 
1169  *          or %NULL if an error occurred.
1170  *
1171  * Since: 2.4
1172  */
1173 gchar *
1174 g_file_read_link (const gchar *filename,
1175                   GError     **error)
1176 {
1177 #ifdef HAVE_READLINK
1178   gchar *buffer;
1179   guint size;
1180   gint read_size;    
1181   
1182   size = 256; 
1183   buffer = g_malloc (size);
1184   
1185   while (TRUE) 
1186     {
1187       read_size = readlink (filename, buffer, size);
1188       if (read_size < 0) {
1189         gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
1190                                                    NULL, NULL, NULL);
1191         g_free (buffer);
1192         g_set_error (error,
1193                      G_FILE_ERROR,
1194                      g_file_error_from_errno (errno),
1195                      _("Failed to read the symbolic link '%s': %s"),
1196                      utf8_filename ? utf8_filename : "???", 
1197                      g_strerror (errno));
1198         g_free (utf8_filename);
1199         
1200         return NULL;
1201       }
1202     
1203       if (read_size < size) 
1204         {
1205           buffer[read_size] = 0;
1206           return buffer;
1207         }
1208       
1209       size *= 2;
1210       buffer = g_realloc (buffer, size);
1211     }
1212 #else
1213   g_set_error (error,
1214                G_FILE_ERROR,
1215                G_FILE_ERROR_INVAL,
1216                _("Symbolic links not supported"));
1217         
1218   return NULL;
1219 #endif
1220 }