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