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