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