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