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