Bug 566348 - g_file_open_tmp uses the wrong g_mkstemp on win32
[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
802  * @length: location to store length in bytes of the contents, or %NULL
803  * @error: return location for a #GError, or %NULL
804  * 
805  * Reads an entire file into allocated memory, with good error
806  * checking. 
807  *
808  * If the call was successful, it returns %TRUE and sets @contents to the file 
809  * contents and @length to the length of the file contents in bytes. The string 
810  * stored in @contents will be nul-terminated, so for text files you can pass 
811  * %NULL for the @length argument. If the call was not successful, it returns 
812  * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error  
813  * codes are those in the #GFileError enumeration. In the error case, 
814  * @contents is set to %NULL and @length is set to zero.
815  *
816  * Return value: %TRUE on success, %FALSE if an error occurred
817  **/
818 gboolean
819 g_file_get_contents (const gchar  *filename,
820                      gchar       **contents,
821                      gsize        *length,
822                      GError      **error)
823 {  
824   g_return_val_if_fail (filename != NULL, FALSE);
825   g_return_val_if_fail (contents != NULL, FALSE);
826
827   *contents = NULL;
828   if (length)
829     *length = 0;
830
831 #ifdef G_OS_WIN32
832   return get_contents_win32 (filename, contents, length, error);
833 #else
834   return get_contents_posix (filename, contents, length, error);
835 #endif
836 }
837
838 static gboolean
839 rename_file (const char  *old_name,
840              const char  *new_name,
841              GError     **err)
842 {
843   errno = 0;
844   if (g_rename (old_name, new_name) == -1)
845     {
846       int save_errno = errno;
847       gchar *display_old_name = g_filename_display_name (old_name);
848       gchar *display_new_name = g_filename_display_name (new_name);
849
850       g_set_error (err,
851                    G_FILE_ERROR,
852                    g_file_error_from_errno (save_errno),
853                    _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
854                    display_old_name,
855                    display_new_name,
856                    g_strerror (save_errno));
857
858       g_free (display_old_name);
859       g_free (display_new_name);
860       
861       return FALSE;
862     }
863   
864   return TRUE;
865 }
866
867 static gchar *
868 write_to_temp_file (const gchar  *contents,
869                     gssize        length,
870                     const gchar  *template,
871                     GError      **err)
872 {
873   gchar *tmp_name;
874   gchar *display_name;
875   gchar *retval;
876   FILE *file;
877   gint fd;
878   int save_errno;
879
880   retval = NULL;
881   
882   tmp_name = g_strdup_printf ("%s.XXXXXX", template);
883
884   errno = 0;
885   fd = create_temp_file (tmp_name, 0666);
886   save_errno = errno;
887
888   display_name = g_filename_display_name (tmp_name);
889       
890   if (fd == -1)
891     {
892       g_set_error (err,
893                    G_FILE_ERROR,
894                    g_file_error_from_errno (save_errno),
895                    _("Failed to create file '%s': %s"),
896                    display_name, g_strerror (save_errno));
897       
898       goto out;
899     }
900
901   errno = 0;
902   file = fdopen (fd, "wb");
903   if (!file)
904     {
905       save_errno = errno;
906       g_set_error (err,
907                    G_FILE_ERROR,
908                    g_file_error_from_errno (save_errno),
909                    _("Failed to open file '%s' for writing: fdopen() failed: %s"),
910                    display_name,
911                    g_strerror (save_errno));
912
913       close (fd);
914       g_unlink (tmp_name);
915       
916       goto out;
917     }
918
919   if (length > 0)
920     {
921       gsize n_written;
922       
923       errno = 0;
924
925       n_written = fwrite (contents, 1, length, file);
926
927       if (n_written < length)
928         {
929           save_errno = errno;
930       
931           g_set_error (err,
932                        G_FILE_ERROR,
933                        g_file_error_from_errno (save_errno),
934                        _("Failed to write file '%s': fwrite() failed: %s"),
935                        display_name,
936                        g_strerror (save_errno));
937
938           fclose (file);
939           g_unlink (tmp_name);
940           
941           goto out;
942         }
943     }
944    
945   errno = 0;
946   if (fclose (file) == EOF)
947     { 
948       save_errno = 0;
949       
950       g_set_error (err,
951                    G_FILE_ERROR,
952                    g_file_error_from_errno (save_errno),
953                    _("Failed to close file '%s': fclose() failed: %s"),
954                    display_name, 
955                    g_strerror (save_errno));
956
957       g_unlink (tmp_name);
958       
959       goto out;
960     }
961
962   retval = g_strdup (tmp_name);
963   
964  out:
965   g_free (tmp_name);
966   g_free (display_name);
967   
968   return retval;
969 }
970
971 /**
972  * g_file_set_contents:
973  * @filename: name of a file to write @contents to, in the GLib file name
974  *   encoding
975  * @contents: string to write to the file
976  * @length: length of @contents, or -1 if @contents is a nul-terminated string
977  * @error: return location for a #GError, or %NULL
978  *
979  * Writes all of @contents to a file named @filename, with good error checking.
980  * If a file called @filename already exists it will be overwritten.
981  *
982  * This write is atomic in the sense that it is first written to a temporary
983  * file which is then renamed to the final name. Notes:
984  * <itemizedlist>
985  * <listitem>
986  *    On Unix, if @filename already exists hard links to @filename will break.
987  *    Also since the file is recreated, existing permissions, access control
988  *    lists, metadata etc. may be lost. If @filename is a symbolic link,
989  *    the link itself will be replaced, not the linked file.
990  * </listitem>
991  * <listitem>
992  *   On Windows renaming a file will not remove an existing file with the
993  *   new name, so on Windows there is a race condition between the existing
994  *   file being removed and the temporary file being renamed.
995  * </listitem>
996  * <listitem>
997  *   On Windows there is no way to remove a file that is open to some
998  *   process, or mapped into memory. Thus, this function will fail if
999  *   @filename already exists and is open.
1000  * </listitem>
1001  * </itemizedlist>
1002  *
1003  * If the call was sucessful, it returns %TRUE. If the call was not successful,
1004  * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1005  * Possible error codes are those in the #GFileError enumeration.
1006  *
1007  * Return value: %TRUE on success, %FALSE if an error occurred
1008  *
1009  * Since: 2.8
1010  **/
1011 gboolean
1012 g_file_set_contents (const gchar  *filename,
1013                      const gchar  *contents,
1014                      gssize        length,
1015                      GError      **error)
1016 {
1017   gchar *tmp_filename;
1018   gboolean retval;
1019   GError *rename_error = NULL;
1020   
1021   g_return_val_if_fail (filename != NULL, FALSE);
1022   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1023   g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1024   g_return_val_if_fail (length >= -1, FALSE);
1025   
1026   if (length == -1)
1027     length = strlen (contents);
1028
1029   tmp_filename = write_to_temp_file (contents, length, filename, error);
1030   
1031   if (!tmp_filename)
1032     {
1033       retval = FALSE;
1034       goto out;
1035     }
1036
1037   if (!rename_file (tmp_filename, filename, &rename_error))
1038     {
1039 #ifndef G_OS_WIN32
1040
1041       g_unlink (tmp_filename);
1042       g_propagate_error (error, rename_error);
1043       retval = FALSE;
1044       goto out;
1045
1046 #else /* G_OS_WIN32 */
1047       
1048       /* Renaming failed, but on Windows this may just mean
1049        * the file already exists. So if the target file
1050        * exists, try deleting it and do the rename again.
1051        */
1052       if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1053         {
1054           g_unlink (tmp_filename);
1055           g_propagate_error (error, rename_error);
1056           retval = FALSE;
1057           goto out;
1058         }
1059
1060       g_error_free (rename_error);
1061       
1062       if (g_unlink (filename) == -1)
1063         {
1064           gchar *display_filename = g_filename_display_name (filename);
1065
1066           int save_errno = errno;
1067           
1068           g_set_error (error,
1069                        G_FILE_ERROR,
1070                        g_file_error_from_errno (save_errno),
1071                        _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1072                        display_filename,
1073                        g_strerror (save_errno));
1074
1075           g_free (display_filename);
1076           g_unlink (tmp_filename);
1077           retval = FALSE;
1078           goto out;
1079         }
1080       
1081       if (!rename_file (tmp_filename, filename, error))
1082         {
1083           g_unlink (tmp_filename);
1084           retval = FALSE;
1085           goto out;
1086         }
1087
1088 #endif
1089     }
1090
1091   retval = TRUE;
1092   
1093  out:
1094   g_free (tmp_filename);
1095   return retval;
1096 }
1097
1098 /*
1099  * create_temp_file based on the mkstemp implementation from the GNU C library.
1100  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1101  */
1102 static gint
1103 create_temp_file (gchar *tmpl, 
1104                   int    permissions)
1105 {
1106   char *XXXXXX;
1107   int count, fd;
1108   static const char letters[] =
1109     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1110   static const int NLETTERS = sizeof (letters) - 1;
1111   glong value;
1112   GTimeVal tv;
1113   static int counter = 0;
1114
1115   /* find the last occurrence of "XXXXXX" */
1116   XXXXXX = g_strrstr (tmpl, "XXXXXX");
1117
1118   if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1119     {
1120       errno = EINVAL;
1121       return -1;
1122     }
1123
1124   /* Get some more or less random data.  */
1125   g_get_current_time (&tv);
1126   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1127
1128   for (count = 0; count < 100; value += 7777, ++count)
1129     {
1130       glong v = value;
1131
1132       /* Fill in the random bits.  */
1133       XXXXXX[0] = letters[v % NLETTERS];
1134       v /= NLETTERS;
1135       XXXXXX[1] = letters[v % NLETTERS];
1136       v /= NLETTERS;
1137       XXXXXX[2] = letters[v % NLETTERS];
1138       v /= NLETTERS;
1139       XXXXXX[3] = letters[v % NLETTERS];
1140       v /= NLETTERS;
1141       XXXXXX[4] = letters[v % NLETTERS];
1142       v /= NLETTERS;
1143       XXXXXX[5] = letters[v % NLETTERS];
1144
1145       /* tmpl is in UTF-8 on Windows, thus use g_open() */
1146       fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, permissions);
1147
1148       if (fd >= 0)
1149         return fd;
1150       else if (errno != EEXIST)
1151         /* Any other error will apply also to other names we might
1152          *  try, and there are 2^32 or so of them, so give up now.
1153          */
1154         return -1;
1155     }
1156
1157   /* We got out of the loop because we ran out of combinations to try.  */
1158   errno = EEXIST;
1159   return -1;
1160 }
1161
1162 /**
1163  * g_mkstemp:
1164  * @tmpl: template filename
1165  *
1166  * Opens a temporary file. See the mkstemp() documentation
1167  * on most UNIX-like systems. 
1168  *
1169  * The parameter is a string that should follow the rules for
1170  * mkstemp() templates, i.e. contain the string "XXXXXX". 
1171  * g_mkstemp() is slightly more flexible than mkstemp()
1172  * in that the sequence does not have to occur at the very end of the 
1173  * template. The X string will 
1174  * be modified to form the name of a file that didn't exist.
1175  * The string should be in the GLib file name encoding. Most importantly, 
1176  * on Windows it should be in UTF-8.
1177  *
1178  * Return value: A file handle (as from open()) to the file
1179  * opened for reading and writing. The file is opened in binary mode
1180  * on platforms where there is a difference. The file handle should be
1181  * closed with close(). In case of errors, -1 is returned.  
1182  */ 
1183 gint
1184 g_mkstemp (gchar *tmpl)
1185 {
1186   return create_temp_file (tmpl, 0600);
1187 }
1188
1189 /**
1190  * g_file_open_tmp:
1191  * @tmpl: Template for file name, as in g_mkstemp(), basename only,
1192  *        or %NULL, to a default template
1193  * @name_used: location to store actual name used, or %NULL
1194  * @error: return location for a #GError
1195  *
1196  * Opens a file for writing in the preferred directory for temporary
1197  * files (as returned by g_get_tmp_dir()). 
1198  *
1199  * @tmpl should be a string in the GLib file name encoding containing 
1200  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1201  * However, unlike these functions, the template should only be a
1202  * basename, no directory components are allowed. If template is
1203  * %NULL, a default template is used.
1204  *
1205  * Note that in contrast to g_mkstemp() (and mkstemp()) 
1206  * @tmpl is not modified, and might thus be a read-only literal string.
1207  *
1208  * The actual name used is returned in @name_used if non-%NULL. This
1209  * string should be freed with g_free() when not needed any longer.
1210  * The returned name is in the GLib file name encoding.
1211  *
1212  * Return value: A file handle (as from open()) to 
1213  * the file opened for reading and writing. The file is opened in binary 
1214  * mode on platforms where there is a difference. The file handle should be
1215  * closed with close(). In case of errors, -1 is returned 
1216  * and @error will be set.
1217  **/
1218 gint
1219 g_file_open_tmp (const gchar  *tmpl,
1220                  gchar       **name_used,
1221                  GError      **error)
1222 {
1223   int retval;
1224   const char *tmpdir;
1225   const char *sep;
1226   char *fulltemplate;
1227   const char *slash;
1228
1229   if (tmpl == NULL)
1230     tmpl = ".XXXXXX";
1231
1232   if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1233 #ifdef G_OS_WIN32
1234       || (strchr (tmpl, '/') != NULL && (slash = "/"))
1235 #endif
1236       )
1237     {
1238       gchar *display_tmpl = g_filename_display_name (tmpl);
1239       char c[2];
1240       c[0] = *slash;
1241       c[1] = '\0';
1242
1243       g_set_error (error,
1244                    G_FILE_ERROR,
1245                    G_FILE_ERROR_FAILED,
1246                    _("Template '%s' invalid, should not contain a '%s'"),
1247                    display_tmpl, c);
1248       g_free (display_tmpl);
1249
1250       return -1;
1251     }
1252   
1253   if (strstr (tmpl, "XXXXXX") == NULL)
1254     {
1255       gchar *display_tmpl = g_filename_display_name (tmpl);
1256       g_set_error (error,
1257                    G_FILE_ERROR,
1258                    G_FILE_ERROR_FAILED,
1259                    _("Template '%s' doesn't contain XXXXXX"),
1260                    display_tmpl);
1261       g_free (display_tmpl);
1262       return -1;
1263     }
1264
1265   tmpdir = g_get_tmp_dir ();
1266
1267   if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1268     sep = "";
1269   else
1270     sep = G_DIR_SEPARATOR_S;
1271
1272   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1273
1274   retval = g_mkstemp (fulltemplate);
1275
1276   if (retval == -1)
1277     {
1278       int save_errno = errno;
1279       gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1280
1281       g_set_error (error,
1282                    G_FILE_ERROR,
1283                    g_file_error_from_errno (save_errno),
1284                    _("Failed to create file '%s': %s"),
1285                    display_fulltemplate, g_strerror (save_errno));
1286       g_free (display_fulltemplate);
1287       g_free (fulltemplate);
1288       return -1;
1289     }
1290
1291   if (name_used)
1292     *name_used = fulltemplate;
1293   else
1294     g_free (fulltemplate);
1295
1296   return retval;
1297 }
1298
1299 static gchar *
1300 g_build_path_va (const gchar  *separator,
1301                  const gchar  *first_element,
1302                  va_list      *args,
1303                  gchar       **str_array)
1304 {
1305   GString *result;
1306   gint separator_len = strlen (separator);
1307   gboolean is_first = TRUE;
1308   gboolean have_leading = FALSE;
1309   const gchar *single_element = NULL;
1310   const gchar *next_element;
1311   const gchar *last_trailing = NULL;
1312   gint i = 0;
1313
1314   result = g_string_new (NULL);
1315
1316   if (str_array)
1317     next_element = str_array[i++];
1318   else
1319     next_element = first_element;
1320
1321   while (TRUE)
1322     {
1323       const gchar *element;
1324       const gchar *start;
1325       const gchar *end;
1326
1327       if (next_element)
1328         {
1329           element = next_element;
1330           if (str_array)
1331             next_element = str_array[i++];
1332           else
1333             next_element = va_arg (*args, gchar *);
1334         }
1335       else
1336         break;
1337
1338       /* Ignore empty elements */
1339       if (!*element)
1340         continue;
1341       
1342       start = element;
1343
1344       if (separator_len)
1345         {
1346           while (start &&
1347                  strncmp (start, separator, separator_len) == 0)
1348             start += separator_len;
1349         }
1350
1351       end = start + strlen (start);
1352       
1353       if (separator_len)
1354         {
1355           while (end >= start + separator_len &&
1356                  strncmp (end - separator_len, separator, separator_len) == 0)
1357             end -= separator_len;
1358           
1359           last_trailing = end;
1360           while (last_trailing >= element + separator_len &&
1361                  strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1362             last_trailing -= separator_len;
1363
1364           if (!have_leading)
1365             {
1366               /* If the leading and trailing separator strings are in the
1367                * same element and overlap, the result is exactly that element
1368                */
1369               if (last_trailing <= start)
1370                 single_element = element;
1371                   
1372               g_string_append_len (result, element, start - element);
1373               have_leading = TRUE;
1374             }
1375           else
1376             single_element = NULL;
1377         }
1378
1379       if (end == start)
1380         continue;
1381
1382       if (!is_first)
1383         g_string_append (result, separator);
1384       
1385       g_string_append_len (result, start, end - start);
1386       is_first = FALSE;
1387     }
1388
1389   if (single_element)
1390     {
1391       g_string_free (result, TRUE);
1392       return g_strdup (single_element);
1393     }
1394   else
1395     {
1396       if (last_trailing)
1397         g_string_append (result, last_trailing);
1398   
1399       return g_string_free (result, FALSE);
1400     }
1401 }
1402
1403 /**
1404  * g_build_pathv:
1405  * @separator: a string used to separator the elements of the path.
1406  * @args: %NULL-terminated array of strings containing the path elements.
1407  * 
1408  * Behaves exactly like g_build_path(), but takes the path elements 
1409  * as a string array, instead of varargs. This function is mainly
1410  * meant for language bindings.
1411  *
1412  * Return value: a newly-allocated string that must be freed with g_free().
1413  *
1414  * Since: 2.8
1415  */
1416 gchar *
1417 g_build_pathv (const gchar  *separator,
1418                gchar       **args)
1419 {
1420   if (!args)
1421     return NULL;
1422
1423   return g_build_path_va (separator, NULL, NULL, args);
1424 }
1425
1426
1427 /**
1428  * g_build_path:
1429  * @separator: a string used to separator the elements of the path.
1430  * @first_element: the first element in the path
1431  * @Varargs: remaining elements in path, terminated by %NULL
1432  * 
1433  * Creates a path from a series of elements using @separator as the
1434  * separator between elements. At the boundary between two elements,
1435  * any trailing occurrences of separator in the first element, or
1436  * leading occurrences of separator in the second element are removed
1437  * and exactly one copy of the separator is inserted.
1438  *
1439  * Empty elements are ignored.
1440  *
1441  * The number of leading copies of the separator on the result is
1442  * the same as the number of leading copies of the separator on
1443  * the first non-empty element.
1444  *
1445  * The number of trailing copies of the separator on the result is
1446  * the same as the number of trailing copies of the separator on
1447  * the last non-empty element. (Determination of the number of
1448  * trailing copies is done without stripping leading copies, so
1449  * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1450  * has 1 trailing copy.)
1451  *
1452  * However, if there is only a single non-empty element, and there
1453  * are no characters in that element not part of the leading or
1454  * trailing separators, then the result is exactly the original value
1455  * of that element.
1456  *
1457  * Other than for determination of the number of leading and trailing
1458  * copies of the separator, elements consisting only of copies
1459  * of the separator are ignored.
1460  * 
1461  * Return value: a newly-allocated string that must be freed with g_free().
1462  **/
1463 gchar *
1464 g_build_path (const gchar *separator,
1465               const gchar *first_element,
1466               ...)
1467 {
1468   gchar *str;
1469   va_list args;
1470
1471   g_return_val_if_fail (separator != NULL, NULL);
1472
1473   va_start (args, first_element);
1474   str = g_build_path_va (separator, first_element, &args, NULL);
1475   va_end (args);
1476
1477   return str;
1478 }
1479
1480 #ifdef G_OS_WIN32
1481
1482 static gchar *
1483 g_build_pathname_va (const gchar  *first_element,
1484                      va_list      *args,
1485                      gchar       **str_array)
1486 {
1487   /* Code copied from g_build_pathv(), and modified to use two
1488    * alternative single-character separators.
1489    */
1490   GString *result;
1491   gboolean is_first = TRUE;
1492   gboolean have_leading = FALSE;
1493   const gchar *single_element = NULL;
1494   const gchar *next_element;
1495   const gchar *last_trailing = NULL;
1496   gchar current_separator = '\\';
1497   gint i = 0;
1498
1499   result = g_string_new (NULL);
1500
1501   if (str_array)
1502     next_element = str_array[i++];
1503   else
1504     next_element = first_element;
1505   
1506   while (TRUE)
1507     {
1508       const gchar *element;
1509       const gchar *start;
1510       const gchar *end;
1511
1512       if (next_element)
1513         {
1514           element = next_element;
1515           if (str_array)
1516             next_element = str_array[i++];
1517           else
1518             next_element = va_arg (*args, gchar *);
1519         }
1520       else
1521         break;
1522
1523       /* Ignore empty elements */
1524       if (!*element)
1525         continue;
1526       
1527       start = element;
1528
1529       if (TRUE)
1530         {
1531           while (start &&
1532                  (*start == '\\' || *start == '/'))
1533             {
1534               current_separator = *start;
1535               start++;
1536             }
1537         }
1538
1539       end = start + strlen (start);
1540       
1541       if (TRUE)
1542         {
1543           while (end >= start + 1 &&
1544                  (end[-1] == '\\' || end[-1] == '/'))
1545             {
1546               current_separator = end[-1];
1547               end--;
1548             }
1549           
1550           last_trailing = end;
1551           while (last_trailing >= element + 1 &&
1552                  (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1553             last_trailing--;
1554
1555           if (!have_leading)
1556             {
1557               /* If the leading and trailing separator strings are in the
1558                * same element and overlap, the result is exactly that element
1559                */
1560               if (last_trailing <= start)
1561                 single_element = element;
1562                   
1563               g_string_append_len (result, element, start - element);
1564               have_leading = TRUE;
1565             }
1566           else
1567             single_element = NULL;
1568         }
1569
1570       if (end == start)
1571         continue;
1572
1573       if (!is_first)
1574         g_string_append_len (result, &current_separator, 1);
1575       
1576       g_string_append_len (result, start, end - start);
1577       is_first = FALSE;
1578     }
1579
1580   if (single_element)
1581     {
1582       g_string_free (result, TRUE);
1583       return g_strdup (single_element);
1584     }
1585   else
1586     {
1587       if (last_trailing)
1588         g_string_append (result, last_trailing);
1589   
1590       return g_string_free (result, FALSE);
1591     }
1592 }
1593
1594 #endif
1595
1596 /**
1597  * g_build_filenamev:
1598  * @args: %NULL-terminated array of strings containing the path elements.
1599  * 
1600  * Behaves exactly like g_build_filename(), but takes the path elements 
1601  * as a string array, instead of varargs. This function is mainly
1602  * meant for language bindings.
1603  *
1604  * Return value: a newly-allocated string that must be freed with g_free().
1605  * 
1606  * Since: 2.8
1607  */
1608 gchar *
1609 g_build_filenamev (gchar **args)
1610 {
1611   gchar *str;
1612
1613 #ifndef G_OS_WIN32
1614   str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1615 #else
1616   str = g_build_pathname_va (NULL, NULL, args);
1617 #endif
1618
1619   return str;
1620 }
1621
1622 /**
1623  * g_build_filename:
1624  * @first_element: the first element in the path
1625  * @Varargs: remaining elements in path, terminated by %NULL
1626  * 
1627  * Creates a filename from a series of elements using the correct
1628  * separator for filenames.
1629  *
1630  * On Unix, this function behaves identically to <literal>g_build_path
1631  * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1632  *
1633  * On Windows, it takes into account that either the backslash
1634  * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1635  * as separator in filenames, but otherwise behaves as on Unix. When
1636  * file pathname separators need to be inserted, the one that last
1637  * previously occurred in the parameters (reading from left to right)
1638  * is used.
1639  *
1640  * No attempt is made to force the resulting filename to be an absolute
1641  * path. If the first element is a relative path, the result will
1642  * be a relative path. 
1643  * 
1644  * Return value: a newly-allocated string that must be freed with g_free().
1645  **/
1646 gchar *
1647 g_build_filename (const gchar *first_element, 
1648                   ...)
1649 {
1650   gchar *str;
1651   va_list args;
1652
1653   va_start (args, first_element);
1654 #ifndef G_OS_WIN32
1655   str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1656 #else
1657   str = g_build_pathname_va (first_element, &args, NULL);
1658 #endif
1659   va_end (args);
1660
1661   return str;
1662 }
1663
1664 #define KILOBYTE_FACTOR 1024.0
1665 #define MEGABYTE_FACTOR (1024.0 * 1024.0)
1666 #define GIGABYTE_FACTOR (1024.0 * 1024.0 * 1024.0)
1667
1668 /**
1669  * g_format_size_for_display:
1670  * @size: a size in bytes.
1671  * 
1672  * Formats a size (for example the size of a file) into a human readable string.
1673  * Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed 
1674  * rounded to the nearest  tenth. E.g. the file size 3292528 bytes will be
1675  * converted into the string "3.1 MB".
1676  *
1677  * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
1678  *
1679  * This string should be freed with g_free() when not needed any longer.
1680  *
1681  * Returns: a newly-allocated formatted string containing a human readable
1682  *          file size.
1683  *
1684  * Since: 2.16
1685  **/
1686 char *
1687 g_format_size_for_display (goffset size)
1688 {
1689   if (size < (goffset) KILOBYTE_FACTOR)
1690     return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
1691   else
1692     {
1693       gdouble displayed_size;
1694       
1695       if (size < (goffset) MEGABYTE_FACTOR)
1696         {
1697           displayed_size = (gdouble) size / KILOBYTE_FACTOR;
1698           return g_strdup_printf (_("%.1f KB"), displayed_size);
1699         }
1700       else if (size < (goffset) GIGABYTE_FACTOR)
1701         {
1702           displayed_size = (gdouble) size / MEGABYTE_FACTOR;
1703           return g_strdup_printf (_("%.1f MB"), displayed_size);
1704         }
1705       else
1706         {
1707           displayed_size = (gdouble) size / GIGABYTE_FACTOR;
1708           return g_strdup_printf (_("%.1f GB"), displayed_size);
1709         }
1710     }
1711 }
1712
1713
1714 /**
1715  * g_file_read_link:
1716  * @filename: the symbolic link
1717  * @error: return location for a #GError
1718  *
1719  * Reads the contents of the symbolic link @filename like the POSIX
1720  * readlink() function.  The returned string is in the encoding used
1721  * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1722  *
1723  * Returns: A newly-allocated string with the contents of the symbolic link, 
1724  *          or %NULL if an error occurred.
1725  *
1726  * Since: 2.4
1727  */
1728 gchar *
1729 g_file_read_link (const gchar  *filename,
1730                   GError      **error)
1731 {
1732 #ifdef HAVE_READLINK
1733   gchar *buffer;
1734   guint size;
1735   gint read_size;    
1736   
1737   size = 256; 
1738   buffer = g_malloc (size);
1739   
1740   while (TRUE) 
1741     {
1742       read_size = readlink (filename, buffer, size);
1743       if (read_size < 0) {
1744         int save_errno = errno;
1745         gchar *display_filename = g_filename_display_name (filename);
1746
1747         g_free (buffer);
1748         g_set_error (error,
1749                      G_FILE_ERROR,
1750                      g_file_error_from_errno (save_errno),
1751                      _("Failed to read the symbolic link '%s': %s"),
1752                      display_filename, 
1753                      g_strerror (save_errno));
1754         g_free (display_filename);
1755         
1756         return NULL;
1757       }
1758     
1759       if (read_size < size) 
1760         {
1761           buffer[read_size] = 0;
1762           return buffer;
1763         }
1764       
1765       size *= 2;
1766       buffer = g_realloc (buffer, size);
1767     }
1768 #else
1769   g_set_error_literal (error,
1770                        G_FILE_ERROR,
1771                        G_FILE_ERROR_INVAL,
1772                        _("Symbolic links not supported"));
1773         
1774   return NULL;
1775 #endif
1776 }
1777
1778 /* NOTE : Keep this part last to ensure nothing in this file uses the
1779  * below binary compatibility versions.
1780  */
1781 #if defined (G_OS_WIN32) && !defined (_WIN64)
1782
1783 /* Binary compatibility versions. Will be called by code compiled
1784  * against quite old (pre-2.8, I think) headers only, not from more
1785  * recently compiled code.
1786  */
1787
1788 #undef g_file_test
1789
1790 gboolean
1791 g_file_test (const gchar *filename,
1792              GFileTest    test)
1793 {
1794   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
1795   gboolean retval;
1796
1797   if (utf8_filename == NULL)
1798     return FALSE;
1799
1800   retval = g_file_test_utf8 (utf8_filename, test);
1801
1802   g_free (utf8_filename);
1803
1804   return retval;
1805 }
1806
1807 #undef g_file_get_contents
1808
1809 gboolean
1810 g_file_get_contents (const gchar  *filename,
1811                      gchar       **contents,
1812                      gsize        *length,
1813                      GError      **error)
1814 {
1815   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
1816   gboolean retval;
1817
1818   if (utf8_filename == NULL)
1819     return FALSE;
1820
1821   retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
1822
1823   g_free (utf8_filename);
1824
1825   return retval;
1826 }
1827
1828 #undef g_mkstemp
1829
1830 gint
1831 g_mkstemp (gchar *tmpl)
1832 {
1833   char *XXXXXX;
1834   int count, fd;
1835   static const char letters[] =
1836     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1837   static const int NLETTERS = sizeof (letters) - 1;
1838   glong value;
1839   GTimeVal tv;
1840   static int counter = 0;
1841
1842   /* find the last occurrence of 'XXXXXX' */
1843   XXXXXX = g_strrstr (tmpl, "XXXXXX");
1844
1845   if (!XXXXXX)
1846     {
1847       errno = EINVAL;
1848       return -1;
1849     }
1850
1851   /* Get some more or less random data.  */
1852   g_get_current_time (&tv);
1853   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1854
1855   for (count = 0; count < 100; value += 7777, ++count)
1856     {
1857       glong v = value;
1858
1859       /* Fill in the random bits.  */
1860       XXXXXX[0] = letters[v % NLETTERS];
1861       v /= NLETTERS;
1862       XXXXXX[1] = letters[v % NLETTERS];
1863       v /= NLETTERS;
1864       XXXXXX[2] = letters[v % NLETTERS];
1865       v /= NLETTERS;
1866       XXXXXX[3] = letters[v % NLETTERS];
1867       v /= NLETTERS;
1868       XXXXXX[4] = letters[v % NLETTERS];
1869       v /= NLETTERS;
1870       XXXXXX[5] = letters[v % NLETTERS];
1871
1872       /* This is the backward compatibility system codepage version,
1873        * thus use normal open().
1874        */
1875       fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1876
1877       if (fd >= 0)
1878         return fd;
1879       else if (errno != EEXIST)
1880         /* Any other error will apply also to other names we might
1881          *  try, and there are 2^32 or so of them, so give up now.
1882          */
1883         return -1;
1884     }
1885
1886   /* We got out of the loop because we ran out of combinations to try.  */
1887   errno = EEXIST;
1888   return -1;
1889 }
1890
1891 #undef g_file_open_tmp
1892
1893 gint
1894 g_file_open_tmp (const gchar  *tmpl,
1895                  gchar       **name_used,
1896                  GError      **error)
1897 {
1898   gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1899   gchar *utf8_name_used;
1900   gint retval;
1901
1902   if (utf8_tmpl == NULL)
1903     return -1;
1904
1905   retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1906   
1907   if (retval == -1)
1908     return -1;
1909
1910   if (name_used)
1911     *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1912
1913   g_free (utf8_name_used);
1914
1915   return retval;
1916 }
1917
1918 #endif
1919
1920 #define __G_FILEUTILS_C__
1921 #include "galiasdef.c"