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