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