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