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