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