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