fcbd63b1bdb7a1595271d7d11113f125c8d39748
[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  * Since: 2.22
1168  */
1169 /*
1170  * g_mkstemp_full based on the mkstemp implementation from the GNU C library.
1171  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1172  */
1173 gint
1174 g_mkstemp_full (gchar *tmpl, 
1175                 int    flags,
1176                 int    mode)
1177 {
1178   char *XXXXXX;
1179   int count, fd;
1180   static const char letters[] =
1181     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1182   static const int NLETTERS = sizeof (letters) - 1;
1183   glong value;
1184   GTimeVal tv;
1185   static int counter = 0;
1186
1187   g_return_val_if_fail (tmpl != NULL, -1);
1188
1189
1190   /* find the last occurrence of "XXXXXX" */
1191   XXXXXX = g_strrstr (tmpl, "XXXXXX");
1192
1193   if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1194     {
1195       errno = EINVAL;
1196       return -1;
1197     }
1198
1199   /* Get some more or less random data.  */
1200   g_get_current_time (&tv);
1201   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1202
1203   for (count = 0; count < 100; value += 7777, ++count)
1204     {
1205       glong v = value;
1206
1207       /* Fill in the random bits.  */
1208       XXXXXX[0] = letters[v % NLETTERS];
1209       v /= NLETTERS;
1210       XXXXXX[1] = letters[v % NLETTERS];
1211       v /= NLETTERS;
1212       XXXXXX[2] = letters[v % NLETTERS];
1213       v /= NLETTERS;
1214       XXXXXX[3] = letters[v % NLETTERS];
1215       v /= NLETTERS;
1216       XXXXXX[4] = letters[v % NLETTERS];
1217       v /= NLETTERS;
1218       XXXXXX[5] = letters[v % NLETTERS];
1219
1220       /* tmpl is in UTF-8 on Windows, thus use g_open() */
1221       fd = g_open (tmpl, flags | O_CREAT | O_EXCL, mode);
1222
1223       if (fd >= 0)
1224         return fd;
1225       else if (errno != EEXIST)
1226         /* Any other error will apply also to other names we might
1227          *  try, and there are 2^32 or so of them, so give up now.
1228          */
1229         return -1;
1230     }
1231
1232   /* We got out of the loop because we ran out of combinations to try.  */
1233   errno = EEXIST;
1234   return -1;
1235 }
1236
1237 /**
1238  * g_mkstemp:
1239  * @tmpl: template filename
1240  *
1241  * Opens a temporary file. See the mkstemp() documentation
1242  * on most UNIX-like systems. 
1243  *
1244  * The parameter is a string that should follow the rules for
1245  * mkstemp() templates, i.e. contain the string "XXXXXX". 
1246  * g_mkstemp() is slightly more flexible than mkstemp()
1247  * in that the sequence does not have to occur at the very end of the 
1248  * template. The X string will 
1249  * be modified to form the name of a file that didn't exist.
1250  * The string should be in the GLib file name encoding. Most importantly, 
1251  * on Windows it should be in UTF-8.
1252  *
1253  * Return value: A file handle (as from open()) to the file
1254  * opened for reading and writing. The file is opened in binary mode
1255  * on platforms where there is a difference. The file handle should be
1256  * closed with close(). In case of errors, -1 is returned.  
1257  */ 
1258 gint
1259 g_mkstemp (gchar *tmpl)
1260 {
1261   return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1262 }
1263
1264 /**
1265  * g_file_open_tmp:
1266  * @tmpl: Template for file name, as in g_mkstemp(), basename only,
1267  *        or %NULL, to a default template
1268  * @name_used: location to store actual name used, or %NULL
1269  * @error: return location for a #GError
1270  *
1271  * Opens a file for writing in the preferred directory for temporary
1272  * files (as returned by g_get_tmp_dir()). 
1273  *
1274  * @tmpl should be a string in the GLib file name encoding containing 
1275  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1276  * However, unlike these functions, the template should only be a
1277  * basename, no directory components are allowed. If template is
1278  * %NULL, a default template is used.
1279  *
1280  * Note that in contrast to g_mkstemp() (and mkstemp()) 
1281  * @tmpl is not modified, and might thus be a read-only literal string.
1282  *
1283  * The actual name used is returned in @name_used if non-%NULL. This
1284  * string should be freed with g_free() when not needed any longer.
1285  * The returned name is in the GLib file name encoding.
1286  *
1287  * Return value: A file handle (as from open()) to 
1288  * the file opened for reading and writing. The file is opened in binary 
1289  * mode on platforms where there is a difference. The file handle should be
1290  * closed with close(). In case of errors, -1 is returned 
1291  * and @error will be set.
1292  **/
1293 gint
1294 g_file_open_tmp (const gchar  *tmpl,
1295                  gchar       **name_used,
1296                  GError      **error)
1297 {
1298   int retval;
1299   const char *tmpdir;
1300   const char *sep;
1301   char *fulltemplate;
1302   const char *slash;
1303
1304   if (tmpl == NULL)
1305     tmpl = ".XXXXXX";
1306
1307   if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1308 #ifdef G_OS_WIN32
1309       || (strchr (tmpl, '/') != NULL && (slash = "/"))
1310 #endif
1311       )
1312     {
1313       gchar *display_tmpl = g_filename_display_name (tmpl);
1314       char c[2];
1315       c[0] = *slash;
1316       c[1] = '\0';
1317
1318       g_set_error (error,
1319                    G_FILE_ERROR,
1320                    G_FILE_ERROR_FAILED,
1321                    _("Template '%s' invalid, should not contain a '%s'"),
1322                    display_tmpl, c);
1323       g_free (display_tmpl);
1324
1325       return -1;
1326     }
1327   
1328   if (strstr (tmpl, "XXXXXX") == NULL)
1329     {
1330       gchar *display_tmpl = g_filename_display_name (tmpl);
1331       g_set_error (error,
1332                    G_FILE_ERROR,
1333                    G_FILE_ERROR_FAILED,
1334                    _("Template '%s' doesn't contain XXXXXX"),
1335                    display_tmpl);
1336       g_free (display_tmpl);
1337       return -1;
1338     }
1339
1340   tmpdir = g_get_tmp_dir ();
1341
1342   if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1343     sep = "";
1344   else
1345     sep = G_DIR_SEPARATOR_S;
1346
1347   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1348
1349   retval = g_mkstemp (fulltemplate);
1350
1351   if (retval == -1)
1352     {
1353       int save_errno = errno;
1354       gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1355
1356       g_set_error (error,
1357                    G_FILE_ERROR,
1358                    g_file_error_from_errno (save_errno),
1359                    _("Failed to create file '%s': %s"),
1360                    display_fulltemplate, g_strerror (save_errno));
1361       g_free (display_fulltemplate);
1362       g_free (fulltemplate);
1363       return -1;
1364     }
1365
1366   if (name_used)
1367     *name_used = fulltemplate;
1368   else
1369     g_free (fulltemplate);
1370
1371   return retval;
1372 }
1373
1374 static gchar *
1375 g_build_path_va (const gchar  *separator,
1376                  const gchar  *first_element,
1377                  va_list      *args,
1378                  gchar       **str_array)
1379 {
1380   GString *result;
1381   gint separator_len = strlen (separator);
1382   gboolean is_first = TRUE;
1383   gboolean have_leading = FALSE;
1384   const gchar *single_element = NULL;
1385   const gchar *next_element;
1386   const gchar *last_trailing = NULL;
1387   gint i = 0;
1388
1389   result = g_string_new (NULL);
1390
1391   if (str_array)
1392     next_element = str_array[i++];
1393   else
1394     next_element = first_element;
1395
1396   while (TRUE)
1397     {
1398       const gchar *element;
1399       const gchar *start;
1400       const gchar *end;
1401
1402       if (next_element)
1403         {
1404           element = next_element;
1405           if (str_array)
1406             next_element = str_array[i++];
1407           else
1408             next_element = va_arg (*args, gchar *);
1409         }
1410       else
1411         break;
1412
1413       /* Ignore empty elements */
1414       if (!*element)
1415         continue;
1416       
1417       start = element;
1418
1419       if (separator_len)
1420         {
1421           while (strncmp (start, separator, separator_len) == 0)
1422             start += separator_len;
1423         }
1424
1425       end = start + strlen (start);
1426       
1427       if (separator_len)
1428         {
1429           while (end >= start + separator_len &&
1430                  strncmp (end - separator_len, separator, separator_len) == 0)
1431             end -= separator_len;
1432           
1433           last_trailing = end;
1434           while (last_trailing >= element + separator_len &&
1435                  strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1436             last_trailing -= separator_len;
1437
1438           if (!have_leading)
1439             {
1440               /* If the leading and trailing separator strings are in the
1441                * same element and overlap, the result is exactly that element
1442                */
1443               if (last_trailing <= start)
1444                 single_element = element;
1445                   
1446               g_string_append_len (result, element, start - element);
1447               have_leading = TRUE;
1448             }
1449           else
1450             single_element = NULL;
1451         }
1452
1453       if (end == start)
1454         continue;
1455
1456       if (!is_first)
1457         g_string_append (result, separator);
1458       
1459       g_string_append_len (result, start, end - start);
1460       is_first = FALSE;
1461     }
1462
1463   if (single_element)
1464     {
1465       g_string_free (result, TRUE);
1466       return g_strdup (single_element);
1467     }
1468   else
1469     {
1470       if (last_trailing)
1471         g_string_append (result, last_trailing);
1472   
1473       return g_string_free (result, FALSE);
1474     }
1475 }
1476
1477 /**
1478  * g_build_pathv:
1479  * @separator: a string used to separator the elements of the path.
1480  * @args: %NULL-terminated array of strings containing the path elements.
1481  * 
1482  * Behaves exactly like g_build_path(), but takes the path elements 
1483  * as a string array, instead of varargs. This function is mainly
1484  * meant for language bindings.
1485  *
1486  * Return value: a newly-allocated string that must be freed with g_free().
1487  *
1488  * Since: 2.8
1489  */
1490 gchar *
1491 g_build_pathv (const gchar  *separator,
1492                gchar       **args)
1493 {
1494   if (!args)
1495     return NULL;
1496
1497   return g_build_path_va (separator, NULL, NULL, args);
1498 }
1499
1500
1501 /**
1502  * g_build_path:
1503  * @separator: a string used to separator the elements of the path.
1504  * @first_element: the first element in the path
1505  * @Varargs: remaining elements in path, terminated by %NULL
1506  * 
1507  * Creates a path from a series of elements using @separator as the
1508  * separator between elements. At the boundary between two elements,
1509  * any trailing occurrences of separator in the first element, or
1510  * leading occurrences of separator in the second element are removed
1511  * and exactly one copy of the separator is inserted.
1512  *
1513  * Empty elements are ignored.
1514  *
1515  * The number of leading copies of the separator on the result is
1516  * the same as the number of leading copies of the separator on
1517  * the first non-empty element.
1518  *
1519  * The number of trailing copies of the separator on the result is
1520  * the same as the number of trailing copies of the separator on
1521  * the last non-empty element. (Determination of the number of
1522  * trailing copies is done without stripping leading copies, so
1523  * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1524  * has 1 trailing copy.)
1525  *
1526  * However, if there is only a single non-empty element, and there
1527  * are no characters in that element not part of the leading or
1528  * trailing separators, then the result is exactly the original value
1529  * of that element.
1530  *
1531  * Other than for determination of the number of leading and trailing
1532  * copies of the separator, elements consisting only of copies
1533  * of the separator are ignored.
1534  * 
1535  * Return value: a newly-allocated string that must be freed with g_free().
1536  **/
1537 gchar *
1538 g_build_path (const gchar *separator,
1539               const gchar *first_element,
1540               ...)
1541 {
1542   gchar *str;
1543   va_list args;
1544
1545   g_return_val_if_fail (separator != NULL, NULL);
1546
1547   va_start (args, first_element);
1548   str = g_build_path_va (separator, first_element, &args, NULL);
1549   va_end (args);
1550
1551   return str;
1552 }
1553
1554 #ifdef G_OS_WIN32
1555
1556 static gchar *
1557 g_build_pathname_va (const gchar  *first_element,
1558                      va_list      *args,
1559                      gchar       **str_array)
1560 {
1561   /* Code copied from g_build_pathv(), and modified to use two
1562    * alternative single-character separators.
1563    */
1564   GString *result;
1565   gboolean is_first = TRUE;
1566   gboolean have_leading = FALSE;
1567   const gchar *single_element = NULL;
1568   const gchar *next_element;
1569   const gchar *last_trailing = NULL;
1570   gchar current_separator = '\\';
1571   gint i = 0;
1572
1573   result = g_string_new (NULL);
1574
1575   if (str_array)
1576     next_element = str_array[i++];
1577   else
1578     next_element = first_element;
1579   
1580   while (TRUE)
1581     {
1582       const gchar *element;
1583       const gchar *start;
1584       const gchar *end;
1585
1586       if (next_element)
1587         {
1588           element = next_element;
1589           if (str_array)
1590             next_element = str_array[i++];
1591           else
1592             next_element = va_arg (*args, gchar *);
1593         }
1594       else
1595         break;
1596
1597       /* Ignore empty elements */
1598       if (!*element)
1599         continue;
1600       
1601       start = element;
1602
1603       if (TRUE)
1604         {
1605           while (start &&
1606                  (*start == '\\' || *start == '/'))
1607             {
1608               current_separator = *start;
1609               start++;
1610             }
1611         }
1612
1613       end = start + strlen (start);
1614       
1615       if (TRUE)
1616         {
1617           while (end >= start + 1 &&
1618                  (end[-1] == '\\' || end[-1] == '/'))
1619             {
1620               current_separator = end[-1];
1621               end--;
1622             }
1623           
1624           last_trailing = end;
1625           while (last_trailing >= element + 1 &&
1626                  (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1627             last_trailing--;
1628
1629           if (!have_leading)
1630             {
1631               /* If the leading and trailing separator strings are in the
1632                * same element and overlap, the result is exactly that element
1633                */
1634               if (last_trailing <= start)
1635                 single_element = element;
1636                   
1637               g_string_append_len (result, element, start - element);
1638               have_leading = TRUE;
1639             }
1640           else
1641             single_element = NULL;
1642         }
1643
1644       if (end == start)
1645         continue;
1646
1647       if (!is_first)
1648         g_string_append_len (result, &current_separator, 1);
1649       
1650       g_string_append_len (result, start, end - start);
1651       is_first = FALSE;
1652     }
1653
1654   if (single_element)
1655     {
1656       g_string_free (result, TRUE);
1657       return g_strdup (single_element);
1658     }
1659   else
1660     {
1661       if (last_trailing)
1662         g_string_append (result, last_trailing);
1663   
1664       return g_string_free (result, FALSE);
1665     }
1666 }
1667
1668 #endif
1669
1670 /**
1671  * g_build_filenamev:
1672  * @args: %NULL-terminated array of strings containing the path elements.
1673  * 
1674  * Behaves exactly like g_build_filename(), but takes the path elements 
1675  * as a string array, instead of varargs. This function is mainly
1676  * meant for language bindings.
1677  *
1678  * Return value: a newly-allocated string that must be freed with g_free().
1679  * 
1680  * Since: 2.8
1681  */
1682 gchar *
1683 g_build_filenamev (gchar **args)
1684 {
1685   gchar *str;
1686
1687 #ifndef G_OS_WIN32
1688   str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1689 #else
1690   str = g_build_pathname_va (NULL, NULL, args);
1691 #endif
1692
1693   return str;
1694 }
1695
1696 /**
1697  * g_build_filename:
1698  * @first_element: the first element in the path
1699  * @Varargs: remaining elements in path, terminated by %NULL
1700  * 
1701  * Creates a filename from a series of elements using the correct
1702  * separator for filenames.
1703  *
1704  * On Unix, this function behaves identically to <literal>g_build_path
1705  * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1706  *
1707  * On Windows, it takes into account that either the backslash
1708  * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1709  * as separator in filenames, but otherwise behaves as on Unix. When
1710  * file pathname separators need to be inserted, the one that last
1711  * previously occurred in the parameters (reading from left to right)
1712  * is used.
1713  *
1714  * No attempt is made to force the resulting filename to be an absolute
1715  * path. If the first element is a relative path, the result will
1716  * be a relative path. 
1717  * 
1718  * Return value: a newly-allocated string that must be freed with g_free().
1719  **/
1720 gchar *
1721 g_build_filename (const gchar *first_element, 
1722                   ...)
1723 {
1724   gchar *str;
1725   va_list args;
1726
1727   va_start (args, first_element);
1728 #ifndef G_OS_WIN32
1729   str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1730 #else
1731   str = g_build_pathname_va (first_element, &args, NULL);
1732 #endif
1733   va_end (args);
1734
1735   return str;
1736 }
1737
1738 #define KILOBYTE_FACTOR 1024.0
1739 #define MEGABYTE_FACTOR (1024.0 * 1024.0)
1740 #define GIGABYTE_FACTOR (1024.0 * 1024.0 * 1024.0)
1741
1742 /**
1743  * g_format_size_for_display:
1744  * @size: a size in bytes.
1745  * 
1746  * Formats a size (for example the size of a file) into a human readable string.
1747  * Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed 
1748  * rounded to the nearest  tenth. E.g. the file size 3292528 bytes will be
1749  * converted into the string "3.1 MB".
1750  *
1751  * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
1752  *
1753  * This string should be freed with g_free() when not needed any longer.
1754  *
1755  * Returns: a newly-allocated formatted string containing a human readable
1756  *          file size.
1757  *
1758  * Since: 2.16
1759  **/
1760 char *
1761 g_format_size_for_display (goffset size)
1762 {
1763   if (size < (goffset) KILOBYTE_FACTOR)
1764     return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
1765   else
1766     {
1767       gdouble displayed_size;
1768       
1769       if (size < (goffset) MEGABYTE_FACTOR)
1770         {
1771           displayed_size = (gdouble) size / KILOBYTE_FACTOR;
1772           return g_strdup_printf (_("%.1f KB"), displayed_size);
1773         }
1774       else if (size < (goffset) GIGABYTE_FACTOR)
1775         {
1776           displayed_size = (gdouble) size / MEGABYTE_FACTOR;
1777           return g_strdup_printf (_("%.1f MB"), displayed_size);
1778         }
1779       else
1780         {
1781           displayed_size = (gdouble) size / GIGABYTE_FACTOR;
1782           return g_strdup_printf (_("%.1f GB"), displayed_size);
1783         }
1784     }
1785 }
1786
1787
1788 /**
1789  * g_file_read_link:
1790  * @filename: the symbolic link
1791  * @error: return location for a #GError
1792  *
1793  * Reads the contents of the symbolic link @filename like the POSIX
1794  * readlink() function.  The returned string is in the encoding used
1795  * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1796  *
1797  * Returns: A newly-allocated string with the contents of the symbolic link, 
1798  *          or %NULL if an error occurred.
1799  *
1800  * Since: 2.4
1801  */
1802 gchar *
1803 g_file_read_link (const gchar  *filename,
1804                   GError      **error)
1805 {
1806 #ifdef HAVE_READLINK
1807   gchar *buffer;
1808   guint size;
1809   gint read_size;    
1810   
1811   size = 256; 
1812   buffer = g_malloc (size);
1813   
1814   while (TRUE) 
1815     {
1816       read_size = readlink (filename, buffer, size);
1817       if (read_size < 0) {
1818         int save_errno = errno;
1819         gchar *display_filename = g_filename_display_name (filename);
1820
1821         g_free (buffer);
1822         g_set_error (error,
1823                      G_FILE_ERROR,
1824                      g_file_error_from_errno (save_errno),
1825                      _("Failed to read the symbolic link '%s': %s"),
1826                      display_filename, 
1827                      g_strerror (save_errno));
1828         g_free (display_filename);
1829         
1830         return NULL;
1831       }
1832     
1833       if (read_size < size) 
1834         {
1835           buffer[read_size] = 0;
1836           return buffer;
1837         }
1838       
1839       size *= 2;
1840       buffer = g_realloc (buffer, size);
1841     }
1842 #else
1843   g_set_error_literal (error,
1844                        G_FILE_ERROR,
1845                        G_FILE_ERROR_INVAL,
1846                        _("Symbolic links not supported"));
1847         
1848   return NULL;
1849 #endif
1850 }
1851
1852 /* NOTE : Keep this part last to ensure nothing in this file uses the
1853  * below binary compatibility versions.
1854  */
1855 #if defined (G_OS_WIN32) && !defined (_WIN64)
1856
1857 /* Binary compatibility versions. Will be called by code compiled
1858  * against quite old (pre-2.8, I think) headers only, not from more
1859  * recently compiled code.
1860  */
1861
1862 #undef g_file_test
1863
1864 gboolean
1865 g_file_test (const gchar *filename,
1866              GFileTest    test)
1867 {
1868   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
1869   gboolean retval;
1870
1871   if (utf8_filename == NULL)
1872     return FALSE;
1873
1874   retval = g_file_test_utf8 (utf8_filename, test);
1875
1876   g_free (utf8_filename);
1877
1878   return retval;
1879 }
1880
1881 #undef g_file_get_contents
1882
1883 gboolean
1884 g_file_get_contents (const gchar  *filename,
1885                      gchar       **contents,
1886                      gsize        *length,
1887                      GError      **error)
1888 {
1889   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
1890   gboolean retval;
1891
1892   if (utf8_filename == NULL)
1893     return FALSE;
1894
1895   retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
1896
1897   g_free (utf8_filename);
1898
1899   return retval;
1900 }
1901
1902 #undef g_mkstemp
1903
1904 gint
1905 g_mkstemp (gchar *tmpl)
1906 {
1907   char *XXXXXX;
1908   int count, fd;
1909   static const char letters[] =
1910     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1911   static const int NLETTERS = sizeof (letters) - 1;
1912   glong value;
1913   GTimeVal tv;
1914   static int counter = 0;
1915
1916   /* find the last occurrence of 'XXXXXX' */
1917   XXXXXX = g_strrstr (tmpl, "XXXXXX");
1918
1919   if (!XXXXXX)
1920     {
1921       errno = EINVAL;
1922       return -1;
1923     }
1924
1925   /* Get some more or less random data.  */
1926   g_get_current_time (&tv);
1927   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1928
1929   for (count = 0; count < 100; value += 7777, ++count)
1930     {
1931       glong v = value;
1932
1933       /* Fill in the random bits.  */
1934       XXXXXX[0] = letters[v % NLETTERS];
1935       v /= NLETTERS;
1936       XXXXXX[1] = letters[v % NLETTERS];
1937       v /= NLETTERS;
1938       XXXXXX[2] = letters[v % NLETTERS];
1939       v /= NLETTERS;
1940       XXXXXX[3] = letters[v % NLETTERS];
1941       v /= NLETTERS;
1942       XXXXXX[4] = letters[v % NLETTERS];
1943       v /= NLETTERS;
1944       XXXXXX[5] = letters[v % NLETTERS];
1945
1946       /* This is the backward compatibility system codepage version,
1947        * thus use normal open().
1948        */
1949       fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1950
1951       if (fd >= 0)
1952         return fd;
1953       else if (errno != EEXIST)
1954         /* Any other error will apply also to other names we might
1955          *  try, and there are 2^32 or so of them, so give up now.
1956          */
1957         return -1;
1958     }
1959
1960   /* We got out of the loop because we ran out of combinations to try.  */
1961   errno = EEXIST;
1962   return -1;
1963 }
1964
1965 #undef g_file_open_tmp
1966
1967 gint
1968 g_file_open_tmp (const gchar  *tmpl,
1969                  gchar       **name_used,
1970                  GError      **error)
1971 {
1972   gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1973   gchar *utf8_name_used;
1974   gint retval;
1975
1976   if (utf8_tmpl == NULL)
1977     return -1;
1978
1979   retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1980   
1981   if (retval == -1)
1982     return -1;
1983
1984   if (name_used)
1985     *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1986
1987   g_free (utf8_name_used);
1988
1989   return retval;
1990 }
1991
1992 #endif
1993
1994 #define __G_FILEUTILS_C__
1995 #include "galiasdef.c"