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