Imported Upstream version 2.74.3
[platform/upstream/glib.git] / glib / gfileutils.c
1 /* gfileutils.c - File utility functions
2  *
3  *  Copyright 2000 Red Hat, Inc.
4  *
5  * SPDX-License-Identifier: LGPL-2.1-or-later
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public License
18  * along with this library; if not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include "config.h"
22 #include "glibconfig.h"
23
24 #include <sys/stat.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <stdarg.h>
28 #include <string.h>
29 #include <errno.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <stdlib.h>
34
35 #ifdef G_OS_UNIX
36 #include <unistd.h>
37 #endif
38 #ifdef G_OS_WIN32
39 #include <windows.h>
40 #include <io.h>
41 #endif /* G_OS_WIN32 */
42
43 #ifndef S_ISLNK
44 #define S_ISLNK(x) 0
45 #endif
46
47 #ifndef O_BINARY
48 #define O_BINARY 0
49 #endif
50
51 #ifndef O_CLOEXEC
52 #define O_CLOEXEC 0
53 #endif
54
55 #include "gfileutils.h"
56
57 #include "gstdio.h"
58 #include "gstdioprivate.h"
59 #include "glibintl.h"
60
61
62 /**
63  * SECTION:fileutils
64  * @title: File Utilities
65  * @short_description: various file-related functions
66  *
67  * Do not use these APIs unless you are porting a POSIX application to Windows.
68  * A more high-level file access API is provided as GIO — see the documentation
69  * for #GFile.
70  *
71  * There is a group of functions which wrap the common POSIX functions
72  * dealing with filenames (g_open(), g_rename(), g_mkdir(), g_stat(),
73  * g_unlink(), g_remove(), g_fopen(), g_freopen()). The point of these
74  * wrappers is to make it possible to handle file names with any Unicode
75  * characters in them on Windows without having to use ifdefs and the
76  * wide character API in the application code.
77  *
78  * On some Unix systems, these APIs may be defined as identical to their POSIX
79  * counterparts. For this reason, you must check for and include the necessary
80  * header files (such as `fcntl.h`) before using functions like g_creat(). You
81  * must also define the relevant feature test macros.
82  *
83  * The pathname argument should be in the GLib file name encoding.
84  * On POSIX this is the actual on-disk encoding which might correspond
85  * to the locale settings of the process (or the `G_FILENAME_ENCODING`
86  * environment variable), or not.
87  *
88  * On Windows the GLib file name encoding is UTF-8. Note that the
89  * Microsoft C library does not use UTF-8, but has separate APIs for
90  * current system code page and wide characters (UTF-16). The GLib
91  * wrappers call the wide character API if present (on modern Windows
92  * systems), otherwise convert to/from the system code page.
93  *
94  * Another group of functions allows to open and read directories
95  * in the GLib file name encoding. These are g_dir_open(),
96  * g_dir_read_name(), g_dir_rewind(), g_dir_close().
97  */
98
99 /**
100  * GFileError:
101  * @G_FILE_ERROR_EXIST: Operation not permitted; only the owner of
102  *     the file (or other resource) or processes with special privileges
103  *     can perform the operation.
104  * @G_FILE_ERROR_ISDIR: File is a directory; you cannot open a directory
105  *     for writing, or create or remove hard links to it.
106  * @G_FILE_ERROR_ACCES: Permission denied; the file permissions do not
107  *     allow the attempted operation.
108  * @G_FILE_ERROR_NAMETOOLONG: Filename too long.
109  * @G_FILE_ERROR_NOENT: No such file or directory. This is a "file
110  *     doesn't exist" error for ordinary files that are referenced in
111  *     contexts where they are expected to already exist.
112  * @G_FILE_ERROR_NOTDIR: A file that isn't a directory was specified when
113  *     a directory is required.
114  * @G_FILE_ERROR_NXIO: No such device or address. The system tried to
115  *     use the device represented by a file you specified, and it
116  *     couldn't find the device. This can mean that the device file was
117  *     installed incorrectly, or that the physical device is missing or
118  *     not correctly attached to the computer.
119  * @G_FILE_ERROR_NODEV: The underlying file system of the specified file
120  *     does not support memory mapping.
121  * @G_FILE_ERROR_ROFS: The directory containing the new link can't be
122  *     modified because it's on a read-only file system.
123  * @G_FILE_ERROR_TXTBSY: Text file busy.
124  * @G_FILE_ERROR_FAULT: You passed in a pointer to bad memory.
125  *     (GLib won't reliably return this, don't pass in pointers to bad
126  *     memory.)
127  * @G_FILE_ERROR_LOOP: Too many levels of symbolic links were encountered
128  *     in looking up a file name. This often indicates a cycle of symbolic
129  *     links.
130  * @G_FILE_ERROR_NOSPC: No space left on device; write operation on a
131  *     file failed because the disk is full.
132  * @G_FILE_ERROR_NOMEM: No memory available. The system cannot allocate
133  *     more virtual memory because its capacity is full.
134  * @G_FILE_ERROR_MFILE: The current process has too many files open and
135  *     can't open any more. Duplicate descriptors do count toward this
136  *     limit.
137  * @G_FILE_ERROR_NFILE: There are too many distinct file openings in the
138  *     entire system.
139  * @G_FILE_ERROR_BADF: Bad file descriptor; for example, I/O on a
140  *     descriptor that has been closed or reading from a descriptor open
141  *     only for writing (or vice versa).
142  * @G_FILE_ERROR_INVAL: Invalid argument. This is used to indicate
143  *     various kinds of problems with passing the wrong argument to a
144  *     library function.
145  * @G_FILE_ERROR_PIPE: Broken pipe; there is no process reading from the
146  *     other end of a pipe. Every library function that returns this
147  *     error code also generates a 'SIGPIPE' signal; this signal
148  *     terminates the program if not handled or blocked. Thus, your
149  *     program will never actually see this code unless it has handled
150  *     or blocked 'SIGPIPE'.
151  * @G_FILE_ERROR_AGAIN: Resource temporarily unavailable; the call might
152  *     work if you try again later.
153  * @G_FILE_ERROR_INTR: Interrupted function call; an asynchronous signal
154  *     occurred and prevented completion of the call. When this
155  *     happens, you should try the call again.
156  * @G_FILE_ERROR_IO: Input/output error; usually used for physical read
157  *    or write errors. i.e. the disk or other physical device hardware
158  *    is returning errors.
159  * @G_FILE_ERROR_PERM: Operation not permitted; only the owner of the
160  *    file (or other resource) or processes with special privileges can
161  *    perform the operation.
162  * @G_FILE_ERROR_NOSYS: Function not implemented; this indicates that
163  *    the system is missing some functionality.
164  * @G_FILE_ERROR_FAILED: Does not correspond to a UNIX error code; this
165  *    is the standard "failed for unspecified reason" error code present
166  *    in all #GError error code enumerations. Returned if no specific
167  *    code applies.
168  *
169  * Values corresponding to @errno codes returned from file operations
170  * on UNIX. Unlike @errno codes, GFileError values are available on
171  * all systems, even Windows. The exact meaning of each code depends
172  * on what sort of file operation you were performing; the UNIX
173  * documentation gives more details. The following error code descriptions
174  * come from the GNU C Library manual, and are under the copyright
175  * of that manual.
176  *
177  * It's not very portable to make detailed assumptions about exactly
178  * which errors will be returned from a given operation. Some errors
179  * don't occur on some systems, etc., sometimes there are subtle
180  * differences in when a system will report a given error, etc.
181  */
182
183 /**
184  * G_FILE_ERROR:
185  *
186  * Error domain for file operations. Errors in this domain will
187  * be from the #GFileError enumeration. See #GError for information
188  * on error domains.
189  */
190
191 /**
192  * GFileTest:
193  * @G_FILE_TEST_IS_REGULAR: %TRUE if the file is a regular file
194  *     (not a directory). Note that this test will also return %TRUE
195  *     if the tested file is a symlink to a regular file.
196  * @G_FILE_TEST_IS_SYMLINK: %TRUE if the file is a symlink.
197  * @G_FILE_TEST_IS_DIR: %TRUE if the file is a directory.
198  * @G_FILE_TEST_IS_EXECUTABLE: %TRUE if the file is executable.
199  * @G_FILE_TEST_EXISTS: %TRUE if the file exists. It may or may not
200  *     be a regular file.
201  *
202  * A test to perform on a file using g_file_test().
203  */
204
205 /**
206  * g_mkdir_with_parents:
207  * @pathname: (type filename): a pathname in the GLib file name encoding
208  * @mode: permissions to use for newly created directories
209  *
210  * Create a directory if it doesn't already exist. Create intermediate
211  * parent directories as needed, too.
212  *
213  * Returns: 0 if the directory already exists, or was successfully
214  * created. Returns -1 if an error occurred, with errno set.
215  *
216  * Since: 2.8
217  */
218 int
219 g_mkdir_with_parents (const gchar *pathname,
220                       int          mode)
221 {
222   gchar *fn, *p;
223
224   if (pathname == NULL || *pathname == '\0')
225     {
226       errno = EINVAL;
227       return -1;
228     }
229
230   /* try to create the full path first */
231   if (g_mkdir (pathname, mode) == 0)
232     return 0;
233   else if (errno == EEXIST)
234     {
235       if (!g_file_test (pathname, G_FILE_TEST_IS_DIR))
236         {
237           errno = ENOTDIR;
238           return -1;
239         }
240       return 0;
241     }
242
243   /* walk the full path and try creating each element */
244   fn = g_strdup (pathname);
245
246   if (g_path_is_absolute (fn))
247     p = (gchar *) g_path_skip_root (fn);
248   else
249     p = fn;
250
251   do
252     {
253       while (*p && !G_IS_DIR_SEPARATOR (*p))
254         p++;
255       
256       if (!*p)
257         p = NULL;
258       else
259         *p = '\0';
260       
261       if (!g_file_test (fn, G_FILE_TEST_EXISTS))
262         {
263           if (g_mkdir (fn, mode) == -1 && errno != EEXIST)
264             {
265               int errno_save = errno;
266               if (errno != ENOENT || !p)
267                 {
268                   g_free (fn);
269                   errno = errno_save;
270                   return -1;
271                 }
272             }
273         }
274       else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
275         {
276           g_free (fn);
277           errno = ENOTDIR;
278           return -1;
279         }
280       if (p)
281         {
282           *p++ = G_DIR_SEPARATOR;
283           while (*p && G_IS_DIR_SEPARATOR (*p))
284             p++;
285         }
286     }
287   while (p);
288
289   g_free (fn);
290
291   return 0;
292 }
293
294 /**
295  * g_file_test:
296  * @filename: (type filename): a filename to test in the
297  *     GLib file name encoding
298  * @test: bitfield of #GFileTest flags
299  *
300  * Returns %TRUE if any of the tests in the bitfield @test are
301  * %TRUE. For example, `(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)`
302  * will return %TRUE if the file exists; the check whether it's a
303  * directory doesn't matter since the existence test is %TRUE. With
304  * the current set of available tests, there's no point passing in
305  * more than one test at a time.
306  *
307  * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
308  * so for a symbolic link to a regular file g_file_test() will return
309  * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
310  *
311  * Note, that for a dangling symbolic link g_file_test() will return
312  * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
313  *
314  * You should never use g_file_test() to test whether it is safe
315  * to perform an operation, because there is always the possibility
316  * of the condition changing before you actually perform the operation.
317  * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
318  * to know whether it is safe to write to a file without being
319  * tricked into writing into a different location. It doesn't work!
320  * |[<!-- language="C" -->
321  *  // DON'T DO THIS
322  *  if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) 
323  *    {
324  *      fd = g_open (filename, O_WRONLY);
325  *      // write to fd
326  *    }
327  * ]|
328  *
329  * Another thing to note is that %G_FILE_TEST_EXISTS and
330  * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
331  * system call. This usually doesn't matter, but if your program
332  * is setuid or setgid it means that these tests will give you
333  * the answer for the real user ID and group ID, rather than the
334  * effective user ID and group ID.
335  *
336  * On Windows, there are no symlinks, so testing for
337  * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
338  * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
339  * its name indicates that it is executable, checking for well-known
340  * extensions and those listed in the `PATHEXT` environment variable.
341  *
342  * Returns: whether a test was %TRUE
343  **/
344 gboolean
345 g_file_test (const gchar *filename,
346              GFileTest    test)
347 {
348 #ifdef G_OS_WIN32
349   DWORD attributes;
350   wchar_t *wfilename;
351 #endif
352
353   g_return_val_if_fail (filename != NULL, FALSE);
354
355 #ifdef G_OS_WIN32
356 /* stuff missing in std vc6 api */
357 #  ifndef INVALID_FILE_ATTRIBUTES
358 #    define INVALID_FILE_ATTRIBUTES -1
359 #  endif
360 #  ifndef FILE_ATTRIBUTE_DEVICE
361 #    define FILE_ATTRIBUTE_DEVICE 64
362 #  endif
363   wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
364
365   if (wfilename == NULL)
366     return FALSE;
367
368   attributes = GetFileAttributesW (wfilename);
369
370   g_free (wfilename);
371
372   if (attributes == INVALID_FILE_ATTRIBUTES)
373     return FALSE;
374
375   if (test & G_FILE_TEST_EXISTS)
376     return TRUE;
377       
378   if (test & G_FILE_TEST_IS_REGULAR)
379     {
380       if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0)
381         return TRUE;
382     }
383
384   if (test & G_FILE_TEST_IS_DIR)
385     {
386       if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
387         return TRUE;
388     }
389
390   /* "while" so that we can exit this "loop" with a simple "break" */
391   while (test & G_FILE_TEST_IS_EXECUTABLE)
392     {
393       const gchar *lastdot = strrchr (filename, '.');
394       const gchar *pathext = NULL, *p;
395       int extlen;
396
397       if (lastdot == NULL)
398         break;
399
400       if (_stricmp (lastdot, ".exe") == 0 ||
401           _stricmp (lastdot, ".cmd") == 0 ||
402           _stricmp (lastdot, ".bat") == 0 ||
403           _stricmp (lastdot, ".com") == 0)
404         return TRUE;
405
406       /* Check if it is one of the types listed in %PATHEXT% */
407
408       pathext = g_getenv ("PATHEXT");
409       if (pathext == NULL)
410         break;
411
412       pathext = g_utf8_casefold (pathext, -1);
413
414       lastdot = g_utf8_casefold (lastdot, -1);
415       extlen = strlen (lastdot);
416
417       p = pathext;
418       while (TRUE)
419         {
420           const gchar *q = strchr (p, ';');
421           if (q == NULL)
422             q = p + strlen (p);
423           if (extlen == q - p &&
424               memcmp (lastdot, p, extlen) == 0)
425             {
426               g_free ((gchar *) pathext);
427               g_free ((gchar *) lastdot);
428               return TRUE;
429             }
430           if (*q)
431             p = q + 1;
432           else
433             break;
434         }
435
436       g_free ((gchar *) pathext);
437       g_free ((gchar *) lastdot);
438       break;
439     }
440
441   return FALSE;
442 #else
443   if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
444     return TRUE;
445   
446   if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
447     {
448       if (getuid () != 0)
449         return TRUE;
450
451       /* For root, on some POSIX systems, access (filename, X_OK)
452        * will succeed even if no executable bits are set on the
453        * file. We fall through to a stat test to avoid that.
454        */
455     }
456   else
457     test &= ~G_FILE_TEST_IS_EXECUTABLE;
458
459   if (test & G_FILE_TEST_IS_SYMLINK)
460     {
461       struct stat s;
462
463       if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
464         return TRUE;
465     }
466   
467   if (test & (G_FILE_TEST_IS_REGULAR |
468               G_FILE_TEST_IS_DIR |
469               G_FILE_TEST_IS_EXECUTABLE))
470     {
471       struct stat s;
472       
473       if (stat (filename, &s) == 0)
474         {
475           if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
476             return TRUE;
477           
478           if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
479             return TRUE;
480
481           /* The extra test for root when access (file, X_OK) succeeds.
482            */
483           if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
484               ((s.st_mode & S_IXOTH) ||
485                (s.st_mode & S_IXUSR) ||
486                (s.st_mode & S_IXGRP)))
487             return TRUE;
488         }
489     }
490
491   return FALSE;
492 #endif
493 }
494
495 G_DEFINE_QUARK (g-file-error-quark, g_file_error)
496
497 /**
498  * g_file_error_from_errno:
499  * @err_no: an "errno" value
500  *
501  * Gets a #GFileError constant based on the passed-in @err_no.
502  *
503  * For example, if you pass in `EEXIST` this function returns
504  * %G_FILE_ERROR_EXIST. Unlike `errno` values, you can portably
505  * assume that all #GFileError values will exist.
506  *
507  * Normally a #GFileError value goes into a #GError returned
508  * from a function that manipulates files. So you would use
509  * g_file_error_from_errno() when constructing a #GError.
510  *
511  * Returns: #GFileError corresponding to the given @err_no
512  **/
513 GFileError
514 g_file_error_from_errno (gint err_no)
515 {
516   switch (err_no)
517     {
518 #ifdef EEXIST
519     case EEXIST:
520       return G_FILE_ERROR_EXIST;
521 #endif
522
523 #ifdef EISDIR
524     case EISDIR:
525       return G_FILE_ERROR_ISDIR;
526 #endif
527
528 #ifdef EACCES
529     case EACCES:
530       return G_FILE_ERROR_ACCES;
531 #endif
532
533 #ifdef ENAMETOOLONG
534     case ENAMETOOLONG:
535       return G_FILE_ERROR_NAMETOOLONG;
536 #endif
537
538 #ifdef ENOENT
539     case ENOENT:
540       return G_FILE_ERROR_NOENT;
541 #endif
542
543 #ifdef ENOTDIR
544     case ENOTDIR:
545       return G_FILE_ERROR_NOTDIR;
546 #endif
547
548 #ifdef ENXIO
549     case ENXIO:
550       return G_FILE_ERROR_NXIO;
551 #endif
552
553 #ifdef ENODEV
554     case ENODEV:
555       return G_FILE_ERROR_NODEV;
556 #endif
557
558 #ifdef EROFS
559     case EROFS:
560       return G_FILE_ERROR_ROFS;
561 #endif
562
563 #ifdef ETXTBSY
564     case ETXTBSY:
565       return G_FILE_ERROR_TXTBSY;
566 #endif
567
568 #ifdef EFAULT
569     case EFAULT:
570       return G_FILE_ERROR_FAULT;
571 #endif
572
573 #ifdef ELOOP
574     case ELOOP:
575       return G_FILE_ERROR_LOOP;
576 #endif
577
578 #ifdef ENOSPC
579     case ENOSPC:
580       return G_FILE_ERROR_NOSPC;
581 #endif
582
583 #ifdef ENOMEM
584     case ENOMEM:
585       return G_FILE_ERROR_NOMEM;
586 #endif
587
588 #ifdef EMFILE
589     case EMFILE:
590       return G_FILE_ERROR_MFILE;
591 #endif
592
593 #ifdef ENFILE
594     case ENFILE:
595       return G_FILE_ERROR_NFILE;
596 #endif
597
598 #ifdef EBADF
599     case EBADF:
600       return G_FILE_ERROR_BADF;
601 #endif
602
603 #ifdef EINVAL
604     case EINVAL:
605       return G_FILE_ERROR_INVAL;
606 #endif
607
608 #ifdef EPIPE
609     case EPIPE:
610       return G_FILE_ERROR_PIPE;
611 #endif
612
613 #ifdef EAGAIN
614     case EAGAIN:
615       return G_FILE_ERROR_AGAIN;
616 #endif
617
618 #ifdef EINTR
619     case EINTR:
620       return G_FILE_ERROR_INTR;
621 #endif
622
623 #ifdef EIO
624     case EIO:
625       return G_FILE_ERROR_IO;
626 #endif
627
628 #ifdef EPERM
629     case EPERM:
630       return G_FILE_ERROR_PERM;
631 #endif
632
633 #ifdef ENOSYS
634     case ENOSYS:
635       return G_FILE_ERROR_NOSYS;
636 #endif
637
638     default:
639       return G_FILE_ERROR_FAILED;
640     }
641 }
642
643 static char *
644 format_error_message (const gchar  *filename,
645                       const gchar  *format_string,
646                       int           saved_errno) G_GNUC_FORMAT(2);
647
648 #pragma GCC diagnostic push
649 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
650
651 static char *
652 format_error_message (const gchar  *filename,
653                       const gchar  *format_string,
654                       int           saved_errno)
655 {
656   gchar *display_name;
657   gchar *msg;
658
659   display_name = g_filename_display_name (filename);
660   msg = g_strdup_printf (format_string, display_name, g_strerror (saved_errno));
661   g_free (display_name);
662
663   return msg;
664 }
665
666 #pragma GCC diagnostic pop
667
668 /* format string must have two '%s':
669  *
670  *   - the place for the filename
671  *   - the place for the strerror
672  */
673 static void
674 set_file_error (GError      **error,
675                 const gchar  *filename,
676                 const gchar  *format_string,
677                 int           saved_errno)
678 {
679   char *msg = format_error_message (filename, format_string, saved_errno);
680
681   g_set_error_literal (error, G_FILE_ERROR, g_file_error_from_errno (saved_errno),
682                        msg);
683   g_free (msg);
684 }
685
686 static gboolean
687 get_contents_stdio (const gchar  *filename,
688                     FILE         *f,
689                     gchar       **contents,
690                     gsize        *length,
691                     GError      **error)
692 {
693   gchar buf[4096];
694   gsize bytes;  /* always <= sizeof(buf) */
695   gchar *str = NULL;
696   gsize total_bytes = 0;
697   gsize total_allocated = 0;
698   gchar *tmp;
699   gchar *display_filename;
700
701   g_assert (f != NULL);
702
703   while (!feof (f))
704     {
705       gint save_errno;
706
707       bytes = fread (buf, 1, sizeof (buf), f);
708       save_errno = errno;
709
710       if (total_bytes > G_MAXSIZE - bytes)
711           goto file_too_large;
712
713       /* Possibility of overflow eliminated above. */
714       while (total_bytes + bytes >= total_allocated)
715         {
716           if (str)
717             {
718               if (total_allocated > G_MAXSIZE / 2)
719                   goto file_too_large;
720               total_allocated *= 2;
721             }
722           else
723             {
724               total_allocated = MIN (bytes + 1, sizeof (buf));
725             }
726
727           tmp = g_try_realloc (str, total_allocated);
728
729           if (tmp == NULL)
730             {
731               display_filename = g_filename_display_name (filename);
732               g_set_error (error,
733                            G_FILE_ERROR,
734                            G_FILE_ERROR_NOMEM,
735                            g_dngettext (GETTEXT_PACKAGE, "Could not allocate %lu byte to read file “%s”", "Could not allocate %lu bytes to read file “%s”", (gulong)total_allocated),
736                            (gulong) total_allocated,
737                            display_filename);
738               g_free (display_filename);
739
740               goto error;
741             }
742
743           str = tmp;
744         }
745
746       if (ferror (f))
747         {
748           display_filename = g_filename_display_name (filename);
749           g_set_error (error,
750                        G_FILE_ERROR,
751                        g_file_error_from_errno (save_errno),
752                        _("Error reading file “%s”: %s"),
753                        display_filename,
754                        g_strerror (save_errno));
755           g_free (display_filename);
756
757           goto error;
758         }
759
760       g_assert (str != NULL);
761       memcpy (str + total_bytes, buf, bytes);
762
763       total_bytes += bytes;
764     }
765
766   fclose (f);
767
768   if (total_allocated == 0)
769     {
770       str = g_new (gchar, 1);
771       total_bytes = 0;
772     }
773
774   str[total_bytes] = '\0';
775
776   if (length)
777     *length = total_bytes;
778
779   *contents = str;
780
781   return TRUE;
782
783  file_too_large:
784   display_filename = g_filename_display_name (filename);
785   g_set_error (error,
786                G_FILE_ERROR,
787                G_FILE_ERROR_FAILED,
788                _("File “%s” is too large"),
789                display_filename);
790   g_free (display_filename);
791
792  error:
793
794   g_free (str);
795   fclose (f);
796
797   return FALSE;
798 }
799
800 #ifndef G_OS_WIN32
801
802 static gboolean
803 get_contents_regfile (const gchar  *filename,
804                       struct stat  *stat_buf,
805                       gint          fd,
806                       gchar       **contents,
807                       gsize        *length,
808                       GError      **error)
809 {
810   gchar *buf;
811   gsize bytes_read;
812   gsize size;
813   gsize alloc_size;
814   gchar *display_filename;
815   
816   size = stat_buf->st_size;
817
818   alloc_size = size + 1;
819   buf = g_try_malloc (alloc_size);
820
821   if (buf == NULL)
822     {
823       display_filename = g_filename_display_name (filename);
824       g_set_error (error,
825                    G_FILE_ERROR,
826                    G_FILE_ERROR_NOMEM,
827                            g_dngettext (GETTEXT_PACKAGE, "Could not allocate %lu byte to read file “%s”", "Could not allocate %lu bytes to read file “%s”", (gulong)alloc_size),
828                    (gulong) alloc_size, 
829                    display_filename);
830       g_free (display_filename);
831       goto error;
832     }
833   
834   bytes_read = 0;
835   while (bytes_read < size)
836     {
837       gssize rc;
838           
839       rc = read (fd, buf + bytes_read, size - bytes_read);
840
841       if (rc < 0)
842         {
843           if (errno != EINTR) 
844             {
845               int save_errno = errno;
846
847               g_free (buf);
848               display_filename = g_filename_display_name (filename);
849               g_set_error (error,
850                            G_FILE_ERROR,
851                            g_file_error_from_errno (save_errno),
852                            _("Failed to read from file “%s”: %s"),
853                            display_filename, 
854                            g_strerror (save_errno));
855               g_free (display_filename);
856               goto error;
857             }
858         }
859       else if (rc == 0)
860         break;
861       else
862         bytes_read += rc;
863     }
864       
865   buf[bytes_read] = '\0';
866
867   if (length)
868     *length = bytes_read;
869   
870   *contents = buf;
871
872   close (fd);
873
874   return TRUE;
875
876  error:
877
878   close (fd);
879   
880   return FALSE;
881 }
882
883 static gboolean
884 get_contents_posix (const gchar  *filename,
885                     gchar       **contents,
886                     gsize        *length,
887                     GError      **error)
888 {
889   struct stat stat_buf;
890   gint fd;
891
892   /* O_BINARY useful on Cygwin */
893   fd = open (filename, O_RDONLY|O_BINARY);
894
895   if (fd < 0)
896     {
897       int saved_errno = errno;
898
899       if (error)
900         set_file_error (error,
901                         filename,
902                         _("Failed to open file “%s”: %s"),
903                         saved_errno);
904
905       return FALSE;
906     }
907
908   /* I don't think this will ever fail, aside from ENOMEM, but. */
909   if (fstat (fd, &stat_buf) < 0)
910     {
911       int saved_errno = errno;
912       if (error)
913         set_file_error (error,
914                         filename,
915                         _("Failed to get attributes of file “%s”: fstat() failed: %s"),
916                         saved_errno);
917       close (fd);
918
919       return FALSE;
920     }
921
922   if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
923     {
924       gboolean retval = get_contents_regfile (filename,
925                                               &stat_buf,
926                                               fd,
927                                               contents,
928                                               length,
929                                               error);
930
931       return retval;
932     }
933   else
934     {
935       FILE *f;
936       gboolean retval;
937
938       f = fdopen (fd, "r");
939       
940       if (f == NULL)
941         {
942           int saved_errno = errno;
943           if (error)
944             set_file_error (error,
945                             filename,
946                             _("Failed to open file “%s”: fdopen() failed: %s"),
947                             saved_errno);
948
949           return FALSE;
950         }
951   
952       retval = get_contents_stdio (filename, f, contents, length, error);
953
954       return retval;
955     }
956 }
957
958 #else  /* G_OS_WIN32 */
959
960 static gboolean
961 get_contents_win32 (const gchar  *filename,
962                     gchar       **contents,
963                     gsize        *length,
964                     GError      **error)
965 {
966   FILE *f;
967   gboolean retval;
968   
969   f = g_fopen (filename, "rb");
970
971   if (f == NULL)
972     {
973       int saved_errno = errno;
974       if (error)
975         set_file_error (error,
976                         filename,
977                         _("Failed to open file “%s”: %s"),
978                         saved_errno);
979
980       return FALSE;
981     }
982   
983   retval = get_contents_stdio (filename, f, contents, length, error);
984
985   return retval;
986 }
987
988 #endif
989
990 /**
991  * g_file_get_contents:
992  * @filename: (type filename): name of a file to read contents from, in the GLib file name encoding
993  * @contents: (out) (array length=length) (element-type guint8): location to store an allocated string, use g_free() to free
994  *     the returned string
995  * @length: (nullable): location to store length in bytes of the contents, or %NULL
996  * @error: return location for a #GError, or %NULL
997  *
998  * Reads an entire file into allocated memory, with good error
999  * checking.
1000  *
1001  * If the call was successful, it returns %TRUE and sets @contents to the file
1002  * contents and @length to the length of the file contents in bytes. The string
1003  * stored in @contents will be nul-terminated, so for text files you can pass
1004  * %NULL for the @length argument. If the call was not successful, it returns
1005  * %FALSE and sets @error. The error domain is %G_FILE_ERROR. Possible error
1006  * codes are those in the #GFileError enumeration. In the error case,
1007  * @contents is set to %NULL and @length is set to zero.
1008  *
1009  * Returns: %TRUE on success, %FALSE if an error occurred
1010  **/
1011 gboolean
1012 g_file_get_contents (const gchar  *filename,
1013                      gchar       **contents,
1014                      gsize        *length,
1015                      GError      **error)
1016 {  
1017   g_return_val_if_fail (filename != NULL, FALSE);
1018   g_return_val_if_fail (contents != NULL, FALSE);
1019
1020   *contents = NULL;
1021   if (length)
1022     *length = 0;
1023
1024 #ifdef G_OS_WIN32
1025   return get_contents_win32 (filename, contents, length, error);
1026 #else
1027   return get_contents_posix (filename, contents, length, error);
1028 #endif
1029 }
1030
1031 static gboolean
1032 rename_file (const char  *old_name,
1033              const char  *new_name,
1034              gboolean     do_fsync,
1035              GError     **err)
1036 {
1037   errno = 0;
1038   if (g_rename (old_name, new_name) == -1)
1039     {
1040       int save_errno = errno;
1041       gchar *display_old_name = g_filename_display_name (old_name);
1042       gchar *display_new_name = g_filename_display_name (new_name);
1043
1044       g_set_error (err,
1045                    G_FILE_ERROR,
1046                    g_file_error_from_errno (save_errno),
1047                    _("Failed to rename file “%s” to “%s”: g_rename() failed: %s"),
1048                    display_old_name,
1049                    display_new_name,
1050                    g_strerror (save_errno));
1051
1052       g_free (display_old_name);
1053       g_free (display_new_name);
1054       
1055       return FALSE;
1056     }
1057
1058   /* In order to guarantee that the *new* contents of the file are seen in
1059    * future, fsync() the directory containing the file. Otherwise if the file
1060    * system was unmounted cleanly now, it would be undefined whether the old
1061    * or new contents of the file were visible after recovery.
1062    *
1063    * This assumes the @old_name and @new_name are in the same directory. */
1064 #ifdef HAVE_FSYNC
1065   if (do_fsync)
1066     {
1067       gchar *dir = g_path_get_dirname (new_name);
1068       int dir_fd = g_open (dir, O_RDONLY, 0);
1069
1070       if (dir_fd >= 0)
1071         {
1072           g_fsync (dir_fd);
1073           g_close (dir_fd, NULL);
1074         }
1075
1076       g_free (dir);
1077     }
1078 #endif  /* HAVE_FSYNC */
1079
1080   return TRUE;
1081 }
1082
1083 static gboolean
1084 fd_should_be_fsynced (int                    fd,
1085                       const gchar           *test_file,
1086                       GFileSetContentsFlags  flags)
1087 {
1088 #ifdef HAVE_FSYNC
1089   struct stat statbuf;
1090
1091   /* If the final destination exists and is > 0 bytes, we want to sync the
1092    * newly written file to ensure the data is on disk when we rename over
1093    * the destination. Otherwise if we get a system crash we can lose both
1094    * the new and the old file on some filesystems. (I.E. those that don't
1095    * guarantee the data is written to the disk before the metadata.)
1096    *
1097    * There is no difference (in file system terms) if the old file doesn’t
1098    * already exist, apart from the fact that if the system crashes and the new
1099    * data hasn’t been fsync()ed, there is only one bit of old data to lose (that
1100    * the file didn’t exist in the first place). In some situations, such as
1101    * trashing files, the old file never exists, so it seems reasonable to avoid
1102    * the fsync(). This is not a widely applicable optimisation though.
1103    */
1104   if ((flags & (G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_DURABLE)) &&
1105       (flags & G_FILE_SET_CONTENTS_ONLY_EXISTING))
1106     {
1107       errno = 0;
1108       if (g_lstat (test_file, &statbuf) == 0)
1109         return (statbuf.st_size > 0);
1110       else if (errno == ENOENT)
1111         return FALSE;
1112       else
1113         return TRUE;  /* lstat() failed; be cautious */
1114     }
1115   else
1116     {
1117       return (flags & (G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_DURABLE));
1118     }
1119 #else  /* if !HAVE_FSYNC */
1120   return FALSE;
1121 #endif  /* !HAVE_FSYNC */
1122 }
1123
1124 /* closes @fd once it’s finished (on success or error) */
1125 static gboolean
1126 write_to_file (const gchar  *contents,
1127                gsize         length,
1128                int           fd,
1129                const gchar  *dest_file,
1130                gboolean      do_fsync,
1131                GError      **err)
1132 {
1133 #ifdef HAVE_FALLOCATE
1134   if (length > 0)
1135     {
1136       /* We do this on a 'best effort' basis... It may not be supported
1137        * on the underlying filesystem.
1138        */
1139       (void) fallocate (fd, 0, 0, length);
1140     }
1141 #endif
1142   while (length > 0)
1143     {
1144       gssize s;
1145
1146       s = write (fd, contents, MIN (length, G_MAXSSIZE));
1147
1148       if (s < 0)
1149         {
1150           int saved_errno = errno;
1151           if (saved_errno == EINTR)
1152             continue;
1153
1154           if (err)
1155             set_file_error (err,
1156                             dest_file, _("Failed to write file “%s”: write() failed: %s"),
1157                             saved_errno);
1158           close (fd);
1159
1160           return FALSE;
1161         }
1162
1163       g_assert ((gsize) s <= length);
1164
1165       contents += s;
1166       length -= s;
1167     }
1168
1169
1170 #ifdef HAVE_FSYNC
1171   errno = 0;
1172   if (do_fsync && g_fsync (fd) != 0)
1173     {
1174       int saved_errno = errno;
1175       if (err)
1176         set_file_error (err,
1177                         dest_file, _("Failed to write file “%s”: fsync() failed: %s"),
1178                         saved_errno);
1179       close (fd);
1180
1181       return FALSE;
1182     }
1183 #endif
1184
1185   errno = 0;
1186   if (!g_close (fd, err))
1187     return FALSE;
1188
1189   return TRUE;
1190 }
1191
1192 /**
1193  * g_file_set_contents:
1194  * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1195  *   encoding
1196  * @contents: (array length=length) (element-type guint8): string to write to the file
1197  * @length: length of @contents, or -1 if @contents is a nul-terminated string
1198  * @error: return location for a #GError, or %NULL
1199  *
1200  * Writes all of @contents to a file named @filename. This is a convenience
1201  * wrapper around calling g_file_set_contents_full() with `flags` set to
1202  * `G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING` and
1203  * `mode` set to `0666`.
1204  *
1205  * Returns: %TRUE on success, %FALSE if an error occurred
1206  *
1207  * Since: 2.8
1208  */
1209 gboolean
1210 g_file_set_contents (const gchar  *filename,
1211                      const gchar  *contents,
1212                      gssize        length,
1213                      GError      **error)
1214 {
1215   return g_file_set_contents_full (filename, contents, length,
1216                                    G_FILE_SET_CONTENTS_CONSISTENT |
1217                                    G_FILE_SET_CONTENTS_ONLY_EXISTING,
1218                                    0666, error);
1219 }
1220
1221 /**
1222  * g_file_set_contents_full:
1223  * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1224  *   encoding
1225  * @contents: (array length=length) (element-type guint8): string to write to the file
1226  * @length: length of @contents, or -1 if @contents is a nul-terminated string
1227  * @flags: flags controlling the safety vs speed of the operation
1228  * @mode: file mode, as passed to `open()`; typically this will be `0666`
1229  * @error: return location for a #GError, or %NULL
1230  *
1231  * Writes all of @contents to a file named @filename, with good error checking.
1232  * If a file called @filename already exists it will be overwritten.
1233  *
1234  * @flags control the properties of the write operation: whether it’s atomic,
1235  * and what the tradeoff is between returning quickly or being resilient to
1236  * system crashes.
1237  *
1238  * As this function performs file I/O, it is recommended to not call it anywhere
1239  * where blocking would cause problems, such as in the main loop of a graphical
1240  * application. In particular, if @flags has any value other than
1241  * %G_FILE_SET_CONTENTS_NONE then this function may call `fsync()`.
1242  *
1243  * If %G_FILE_SET_CONTENTS_CONSISTENT is set in @flags, the operation is atomic
1244  * in the sense that it is first written to a temporary file which is then
1245  * renamed to the final name.
1246  *
1247  * Notes:
1248  *
1249  * - On UNIX, if @filename already exists hard links to @filename will break.
1250  *   Also since the file is recreated, existing permissions, access control
1251  *   lists, metadata etc. may be lost. If @filename is a symbolic link,
1252  *   the link itself will be replaced, not the linked file.
1253  *
1254  * - On UNIX, if @filename already exists and is non-empty, and if the system
1255  *   supports it (via a journalling filesystem or equivalent), and if
1256  *   %G_FILE_SET_CONTENTS_CONSISTENT is set in @flags, the `fsync()` call (or
1257  *   equivalent) will be used to ensure atomic replacement: @filename
1258  *   will contain either its old contents or @contents, even in the face of
1259  *   system power loss, the disk being unsafely removed, etc.
1260  *
1261  * - On UNIX, if @filename does not already exist or is empty, there is a
1262  *   possibility that system power loss etc. after calling this function will
1263  *   leave @filename empty or full of NUL bytes, depending on the underlying
1264  *   filesystem, unless %G_FILE_SET_CONTENTS_DURABLE and
1265  *   %G_FILE_SET_CONTENTS_CONSISTENT are set in @flags.
1266  *
1267  * - On Windows renaming a file will not remove an existing file with the
1268  *   new name, so on Windows there is a race condition between the existing
1269  *   file being removed and the temporary file being renamed.
1270  *
1271  * - On Windows there is no way to remove a file that is open to some
1272  *   process, or mapped into memory. Thus, this function will fail if
1273  *   @filename already exists and is open.
1274  *
1275  * If the call was successful, it returns %TRUE. If the call was not successful,
1276  * it returns %FALSE and sets @error. The error domain is %G_FILE_ERROR.
1277  * Possible error codes are those in the #GFileError enumeration.
1278  *
1279  * Note that the name for the temporary file is constructed by appending up
1280  * to 7 characters to @filename.
1281  *
1282  * If the file didn’t exist before and is created, it will be given the
1283  * permissions from @mode. Otherwise, the permissions of the existing file may
1284  * be changed to @mode depending on @flags, or they may remain unchanged.
1285  *
1286  * Returns: %TRUE on success, %FALSE if an error occurred
1287  *
1288  * Since: 2.66
1289  */
1290 gboolean
1291 g_file_set_contents_full (const gchar            *filename,
1292                           const gchar            *contents,
1293                           gssize                  length,
1294                           GFileSetContentsFlags   flags,
1295                           int                     mode,
1296                           GError                **error)
1297 {
1298   g_return_val_if_fail (filename != NULL, FALSE);
1299   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1300   g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1301   g_return_val_if_fail (length >= -1, FALSE);
1302
1303   /* @flags are handled as follows:
1304    *  - %G_FILE_SET_CONTENTS_NONE: write directly to @filename, no fsync()s
1305    *  - %G_FILE_SET_CONTENTS_CONSISTENT: write to temp file, fsync() it, rename()
1306    *  - %G_FILE_SET_CONTENTS_CONSISTENT | ONLY_EXISTING: as above, but skip the
1307    *    fsync() if @filename doesn’t exist or is empty
1308    *  - %G_FILE_SET_CONTENTS_DURABLE: write directly to @filename, fsync() it
1309    *  - %G_FILE_SET_CONTENTS_DURABLE | ONLY_EXISTING: as above, but skip the
1310    *    fsync() if @filename doesn’t exist or is empty
1311    *  - %G_FILE_SET_CONTENTS_CONSISTENT | DURABLE: write to temp file, fsync()
1312    *    it, rename(), fsync() containing directory
1313    *  - %G_FILE_SET_CONTENTS_CONSISTENT | DURABLE | ONLY_EXISTING: as above, but
1314    *    skip both fsync()s if @filename doesn’t exist or is empty
1315    */
1316
1317   if (length < 0)
1318     length = strlen (contents);
1319
1320   if (flags & G_FILE_SET_CONTENTS_CONSISTENT)
1321     {
1322       gchar *tmp_filename = NULL;
1323       GError *rename_error = NULL;
1324       gboolean retval;
1325       int fd;
1326       gboolean do_fsync;
1327
1328       tmp_filename = g_strdup_printf ("%s.XXXXXX", filename);
1329
1330       errno = 0;
1331       fd = g_mkstemp_full (tmp_filename, O_RDWR | O_BINARY, mode);
1332
1333       if (fd == -1)
1334         {
1335           int saved_errno = errno;
1336           if (error)
1337             set_file_error (error,
1338                             tmp_filename, _("Failed to create file “%s”: %s"),
1339                             saved_errno);
1340           retval = FALSE;
1341           goto consistent_out;
1342         }
1343
1344       do_fsync = fd_should_be_fsynced (fd, filename, flags);
1345       if (!write_to_file (contents, length, g_steal_fd (&fd), tmp_filename, do_fsync, error))
1346         {
1347           g_unlink (tmp_filename);
1348           retval = FALSE;
1349           goto consistent_out;
1350         }
1351
1352       if (!rename_file (tmp_filename, filename, do_fsync, &rename_error))
1353         {
1354 #ifndef G_OS_WIN32
1355
1356           g_unlink (tmp_filename);
1357           g_propagate_error (error, rename_error);
1358           retval = FALSE;
1359           goto consistent_out;
1360
1361 #else /* G_OS_WIN32 */
1362
1363           /* Renaming failed, but on Windows this may just mean
1364            * the file already exists. So if the target file
1365            * exists, try deleting it and do the rename again.
1366            */
1367           if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1368             {
1369               g_unlink (tmp_filename);
1370               g_propagate_error (error, rename_error);
1371               retval = FALSE;
1372               goto consistent_out;
1373             }
1374
1375           g_error_free (rename_error);
1376
1377           if (g_unlink (filename) == -1)
1378             {
1379               int saved_errno = errno;
1380               if (error)
1381                 set_file_error (error,
1382                                 filename,
1383                                 _("Existing file “%s” could not be removed: g_unlink() failed: %s"),
1384                                 saved_errno);
1385               g_unlink (tmp_filename);
1386               retval = FALSE;
1387               goto consistent_out;
1388             }
1389
1390           if (!rename_file (tmp_filename, filename, flags, error))
1391             {
1392               g_unlink (tmp_filename);
1393               retval = FALSE;
1394               goto consistent_out;
1395             }
1396
1397 #endif  /* G_OS_WIN32 */
1398         }
1399
1400       retval = TRUE;
1401
1402 consistent_out:
1403       g_free (tmp_filename);
1404       return retval;
1405     }
1406   else
1407     {
1408       int direct_fd;
1409       int open_flags;
1410       gboolean do_fsync;
1411
1412       open_flags = O_RDWR | O_BINARY | O_CREAT | O_CLOEXEC;
1413 #ifdef O_NOFOLLOW
1414       /* Windows doesn’t have symlinks, so O_NOFOLLOW is unnecessary there. */
1415       open_flags |= O_NOFOLLOW;
1416 #endif
1417
1418       errno = 0;
1419       direct_fd = g_open (filename, open_flags, mode);
1420
1421       if (direct_fd < 0)
1422         {
1423           int saved_errno = errno;
1424
1425 #ifdef O_NOFOLLOW
1426           /* ELOOP indicates that @filename is a symlink, since we used
1427            * O_NOFOLLOW (alternately it could indicate that @filename contains
1428            * looping or too many symlinks). In either case, try again on the
1429            * %G_FILE_SET_CONTENTS_CONSISTENT code path.
1430            *
1431            * FreeBSD uses EMLINK instead of ELOOP
1432            * (https://www.freebsd.org/cgi/man.cgi?query=open&sektion=2#STANDARDS),
1433            * and NetBSD uses EFTYPE
1434            * (https://netbsd.gw.com/cgi-bin/man-cgi?open+2+NetBSD-current). */
1435 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1436           if (saved_errno == EMLINK)
1437 #elif defined(__NetBSD__)
1438           if (saved_errno == EFTYPE)
1439 #else
1440           if (saved_errno == ELOOP)
1441 #endif
1442             return g_file_set_contents_full (filename, contents, length,
1443                                              flags | G_FILE_SET_CONTENTS_CONSISTENT,
1444                                              mode, error);
1445 #endif  /* O_NOFOLLOW */
1446
1447           if (error)
1448             set_file_error (error,
1449                             filename, _("Failed to open file “%s”: %s"),
1450                             saved_errno);
1451           return FALSE;
1452         }
1453
1454       do_fsync = fd_should_be_fsynced (direct_fd, filename, flags);
1455       if (!write_to_file (contents, length, g_steal_fd (&direct_fd), filename,
1456                           do_fsync, error))
1457         return FALSE;
1458     }
1459
1460   return TRUE;
1461 }
1462
1463 /*
1464  * get_tmp_file based on the mkstemp implementation from the GNU C library.
1465  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1466  */
1467 typedef gint (*GTmpFileCallback) (const gchar *, gint, gint);
1468
1469 static gint
1470 get_tmp_file (gchar            *tmpl,
1471               GTmpFileCallback  f,
1472               int               flags,
1473               int               mode)
1474 {
1475   char *XXXXXX;
1476   int count, fd;
1477   static const char letters[] =
1478     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1479   static const int NLETTERS = sizeof (letters) - 1;
1480   glong value;
1481   gint64 now_us;
1482   static int counter = 0;
1483
1484   g_return_val_if_fail (tmpl != NULL, -1);
1485
1486   /* find the last occurrence of "XXXXXX" */
1487   XXXXXX = g_strrstr (tmpl, "XXXXXX");
1488
1489   if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1490     {
1491       errno = EINVAL;
1492       return -1;
1493     }
1494
1495   /* Get some more or less random data.  */
1496   now_us = g_get_real_time ();
1497   value = ((now_us % G_USEC_PER_SEC) ^ (now_us / G_USEC_PER_SEC)) + counter++;
1498
1499   for (count = 0; count < 100; value += 7777, ++count)
1500     {
1501       glong v = value;
1502
1503       /* Fill in the random bits.  */
1504       XXXXXX[0] = letters[v % NLETTERS];
1505       v /= NLETTERS;
1506       XXXXXX[1] = letters[v % NLETTERS];
1507       v /= NLETTERS;
1508       XXXXXX[2] = letters[v % NLETTERS];
1509       v /= NLETTERS;
1510       XXXXXX[3] = letters[v % NLETTERS];
1511       v /= NLETTERS;
1512       XXXXXX[4] = letters[v % NLETTERS];
1513       v /= NLETTERS;
1514       XXXXXX[5] = letters[v % NLETTERS];
1515
1516       fd = f (tmpl, flags, mode);
1517
1518       if (fd >= 0)
1519         return fd;
1520       else if (errno != EEXIST)
1521         /* Any other error will apply also to other names we might
1522          *  try, and there are 2^32 or so of them, so give up now.
1523          */
1524         return -1;
1525     }
1526
1527   /* We got out of the loop because we ran out of combinations to try.  */
1528   errno = EEXIST;
1529   return -1;
1530 }
1531
1532 /* Some GTmpFileCallback implementations.
1533  *
1534  * Note: we cannot use open() or g_open() directly because even though
1535  * they appear compatible, they may be vararg functions and calling
1536  * varargs functions through a non-varargs type is undefined.
1537  */
1538 static gint
1539 wrap_g_mkdir (const gchar *filename,
1540               int          flags G_GNUC_UNUSED,
1541               int          mode)
1542 {
1543   /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1544   return g_mkdir (filename, mode);
1545 }
1546
1547 static gint
1548 wrap_g_open (const gchar *filename,
1549                 int          flags,
1550                 int          mode)
1551 {
1552   return g_open (filename, flags, mode);
1553 }
1554
1555 /**
1556  * g_mkdtemp_full: (skip)
1557  * @tmpl: (type filename): template directory name
1558  * @mode: permissions to create the temporary directory with
1559  *
1560  * Creates a temporary directory. See the mkdtemp() documentation
1561  * on most UNIX-like systems.
1562  *
1563  * The parameter is a string that should follow the rules for
1564  * mkdtemp() templates, i.e. contain the string "XXXXXX".
1565  * g_mkdtemp_full() is slightly more flexible than mkdtemp() in that the
1566  * sequence does not have to occur at the very end of the template
1567  * and you can pass a @mode. The X string will be modified to form
1568  * the name of a directory that didn't exist. The string should be
1569  * in the GLib file name encoding. Most importantly, on Windows it
1570  * should be in UTF-8.
1571  *
1572  * If you are going to be creating a temporary directory inside the
1573  * directory returned by g_get_tmp_dir(), you might want to use
1574  * g_dir_make_tmp() instead.
1575  *
1576  * Returns: (nullable) (type filename): A pointer to @tmpl, which has been
1577  *     modified to hold the directory name. In case of errors, %NULL is
1578  *     returned, and %errno will be set.
1579  *
1580  * Since: 2.30
1581  */
1582 gchar *
1583 g_mkdtemp_full (gchar *tmpl,
1584                 gint   mode)
1585 {
1586   if (get_tmp_file (tmpl, wrap_g_mkdir, 0, mode) == -1)
1587     return NULL;
1588   else
1589     return tmpl;
1590 }
1591
1592 /**
1593  * g_mkdtemp: (skip)
1594  * @tmpl: (type filename): template directory name
1595  *
1596  * Creates a temporary directory. See the mkdtemp() documentation
1597  * on most UNIX-like systems.
1598  *
1599  * The parameter is a string that should follow the rules for
1600  * mkdtemp() templates, i.e. contain the string "XXXXXX".
1601  * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1602  * sequence does not have to occur at the very end of the template.
1603  * The X string will be modified to form the name of a directory that
1604  * didn't exist.
1605  * The string should be in the GLib file name encoding. Most importantly,
1606  * on Windows it should be in UTF-8.
1607  *
1608  * If you are going to be creating a temporary directory inside the
1609  * directory returned by g_get_tmp_dir(), you might want to use
1610  * g_dir_make_tmp() instead.
1611  *
1612  * Returns: (nullable) (type filename): A pointer to @tmpl, which has been
1613  *     modified to hold the directory name.  In case of errors, %NULL is
1614  *     returned and %errno will be set.
1615  *
1616  * Since: 2.30
1617  */
1618 gchar *
1619 g_mkdtemp (gchar *tmpl)
1620 {
1621   return g_mkdtemp_full (tmpl, 0700);
1622 }
1623
1624 /**
1625  * g_mkstemp_full: (skip)
1626  * @tmpl: (type filename): template filename
1627  * @flags: flags to pass to an open() call in addition to O_EXCL
1628  *     and O_CREAT, which are passed automatically
1629  * @mode: permissions to create the temporary file with
1630  *
1631  * Opens a temporary file. See the mkstemp() documentation
1632  * on most UNIX-like systems.
1633  *
1634  * The parameter is a string that should follow the rules for
1635  * mkstemp() templates, i.e. contain the string "XXXXXX".
1636  * g_mkstemp_full() is slightly more flexible than mkstemp()
1637  * in that the sequence does not have to occur at the very end of the
1638  * template and you can pass a @mode and additional @flags. The X
1639  * string will be modified to form the name of a file that didn't exist.
1640  * The string should be in the GLib file name encoding. Most importantly,
1641  * on Windows it should be in UTF-8.
1642  *
1643  * Returns: A file handle (as from open()) to the file
1644  *     opened for reading and writing. The file handle should be
1645  *     closed with close(). In case of errors, -1 is returned
1646  *     and %errno will be set.
1647  *
1648  * Since: 2.22
1649  */
1650 gint
1651 g_mkstemp_full (gchar *tmpl,
1652                 gint   flags,
1653                 gint   mode)
1654 {
1655   /* tmpl is in UTF-8 on Windows, thus use g_open() */
1656   return get_tmp_file (tmpl, wrap_g_open,
1657                        flags | O_CREAT | O_EXCL, mode);
1658 }
1659
1660 /**
1661  * g_mkstemp: (skip)
1662  * @tmpl: (type filename): template filename
1663  *
1664  * Opens a temporary file. See the mkstemp() documentation
1665  * on most UNIX-like systems.
1666  *
1667  * The parameter is a string that should follow the rules for
1668  * mkstemp() templates, i.e. contain the string "XXXXXX".
1669  * g_mkstemp() is slightly more flexible than mkstemp() in that the
1670  * sequence does not have to occur at the very end of the template.
1671  * The X string will be modified to form the name of a file that
1672  * didn't exist. The string should be in the GLib file name encoding.
1673  * Most importantly, on Windows it should be in UTF-8.
1674  *
1675  * Returns: A file handle (as from open()) to the file
1676  *     opened for reading and writing. The file is opened in binary
1677  *     mode on platforms where there is a difference. The file handle
1678  *     should be closed with close(). In case of errors, -1 is
1679  *     returned and %errno will be set.
1680  */
1681 gint
1682 g_mkstemp (gchar *tmpl)
1683 {
1684   return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1685 }
1686
1687 static gint
1688 g_get_tmp_name (const gchar      *tmpl,
1689                 gchar           **name_used,
1690                 GTmpFileCallback  f,
1691                 gint              flags,
1692                 gint              mode,
1693                 GError          **error)
1694 {
1695   int retval;
1696   const char *tmpdir;
1697   const char *sep;
1698   char *fulltemplate;
1699   const char *slash;
1700
1701   if (tmpl == NULL)
1702     tmpl = ".XXXXXX";
1703
1704   if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1705 #ifdef G_OS_WIN32
1706       || (strchr (tmpl, '/') != NULL && (slash = "/"))
1707 #endif
1708       )
1709     {
1710       gchar *display_tmpl = g_filename_display_name (tmpl);
1711       char c[2];
1712       c[0] = *slash;
1713       c[1] = '\0';
1714
1715       g_set_error (error,
1716                    G_FILE_ERROR,
1717                    G_FILE_ERROR_FAILED,
1718                    _("Template “%s” invalid, should not contain a “%s”"),
1719                    display_tmpl, c);
1720       g_free (display_tmpl);
1721
1722       return -1;
1723     }
1724
1725   if (strstr (tmpl, "XXXXXX") == NULL)
1726     {
1727       gchar *display_tmpl = g_filename_display_name (tmpl);
1728       g_set_error (error,
1729                    G_FILE_ERROR,
1730                    G_FILE_ERROR_FAILED,
1731                    _("Template “%s” doesn’t contain XXXXXX"),
1732                    display_tmpl);
1733       g_free (display_tmpl);
1734       return -1;
1735     }
1736
1737   tmpdir = g_get_tmp_dir ();
1738
1739   if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1740     sep = "";
1741   else
1742     sep = G_DIR_SEPARATOR_S;
1743
1744   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1745
1746   retval = get_tmp_file (fulltemplate, f, flags, mode);
1747   if (retval == -1)
1748     {
1749       int saved_errno = errno;
1750       if (error)
1751         set_file_error (error,
1752                         fulltemplate,
1753                         _("Failed to create file “%s”: %s"),
1754                         saved_errno);
1755       g_free (fulltemplate);
1756       return -1;
1757     }
1758
1759   *name_used = fulltemplate;
1760
1761   return retval;
1762 }
1763
1764 /**
1765  * g_file_open_tmp:
1766  * @tmpl: (type filename) (nullable): Template for file name, as in
1767  *     g_mkstemp(), basename only, or %NULL for a default template
1768  * @name_used: (out) (type filename): location to store actual name used,
1769  *     or %NULL
1770  * @error: return location for a #GError
1771  *
1772  * Opens a file for writing in the preferred directory for temporary
1773  * files (as returned by g_get_tmp_dir()).
1774  *
1775  * @tmpl should be a string in the GLib file name encoding containing
1776  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1777  * However, unlike these functions, the template should only be a
1778  * basename, no directory components are allowed. If template is
1779  * %NULL, a default template is used.
1780  *
1781  * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
1782  * modified, and might thus be a read-only literal string.
1783  *
1784  * Upon success, and if @name_used is non-%NULL, the actual name used
1785  * is returned in @name_used. This string should be freed with g_free()
1786  * when not needed any longer. The returned name is in the GLib file
1787  * name encoding.
1788  *
1789  * Returns: A file handle (as from open()) to the file opened for
1790  *     reading and writing. The file is opened in binary mode on platforms
1791  *     where there is a difference. The file handle should be closed with
1792  *     close(). In case of errors, -1 is returned and @error will be set.
1793  */
1794 gint
1795 g_file_open_tmp (const gchar  *tmpl,
1796                  gchar       **name_used,
1797                  GError      **error)
1798 {
1799   gchar *fulltemplate;
1800   gint result;
1801
1802   g_return_val_if_fail (error == NULL || *error == NULL, -1);
1803
1804   result = g_get_tmp_name (tmpl, &fulltemplate,
1805                            wrap_g_open,
1806                            O_CREAT | O_EXCL | O_RDWR | O_BINARY,
1807                            0600,
1808                            error);
1809   if (result != -1)
1810     {
1811       if (name_used)
1812         *name_used = fulltemplate;
1813       else
1814         g_free (fulltemplate);
1815     }
1816
1817   return result;
1818 }
1819
1820 /**
1821  * g_dir_make_tmp:
1822  * @tmpl: (type filename) (nullable): Template for directory name,
1823  *     as in g_mkdtemp(), basename only, or %NULL for a default template
1824  * @error: return location for a #GError
1825  *
1826  * Creates a subdirectory in the preferred directory for temporary
1827  * files (as returned by g_get_tmp_dir()).
1828  *
1829  * @tmpl should be a string in the GLib file name encoding containing
1830  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1831  * However, unlike these functions, the template should only be a
1832  * basename, no directory components are allowed. If template is
1833  * %NULL, a default template is used.
1834  *
1835  * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
1836  * modified, and might thus be a read-only literal string.
1837  *
1838  * Returns: (type filename) (transfer full): The actual name used. This string
1839  *     should be freed with g_free() when not needed any longer and is
1840  *     is in the GLib file name encoding. In case of errors, %NULL is
1841  *     returned and @error will be set.
1842  *
1843  * Since: 2.30
1844  */
1845 gchar *
1846 g_dir_make_tmp (const gchar  *tmpl,
1847                 GError      **error)
1848 {
1849   gchar *fulltemplate;
1850
1851   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1852
1853   if (g_get_tmp_name (tmpl, &fulltemplate, wrap_g_mkdir, 0, 0700, error) == -1)
1854     return NULL;
1855   else
1856     return fulltemplate;
1857 }
1858
1859 static gchar *
1860 g_build_path_va (const gchar  *separator,
1861                  const gchar  *first_element,
1862                  va_list      *args,
1863                  gchar       **str_array)
1864 {
1865   GString *result;
1866   gint separator_len = strlen (separator);
1867   gboolean is_first = TRUE;
1868   gboolean have_leading = FALSE;
1869   const gchar *single_element = NULL;
1870   const gchar *next_element;
1871   const gchar *last_trailing = NULL;
1872   gint i = 0;
1873
1874   result = g_string_new (NULL);
1875
1876   if (str_array)
1877     next_element = str_array[i++];
1878   else
1879     next_element = first_element;
1880
1881   while (TRUE)
1882     {
1883       const gchar *element;
1884       const gchar *start;
1885       const gchar *end;
1886
1887       if (next_element)
1888         {
1889           element = next_element;
1890           if (str_array)
1891             next_element = str_array[i++];
1892           else
1893             next_element = va_arg (*args, gchar *);
1894         }
1895       else
1896         break;
1897
1898       /* Ignore empty elements */
1899       if (!*element)
1900         continue;
1901       
1902       start = element;
1903
1904       if (separator_len)
1905         {
1906           while (strncmp (start, separator, separator_len) == 0)
1907             start += separator_len;
1908         }
1909
1910       end = start + strlen (start);
1911       
1912       if (separator_len)
1913         {
1914           while (end >= start + separator_len &&
1915                  strncmp (end - separator_len, separator, separator_len) == 0)
1916             end -= separator_len;
1917           
1918           last_trailing = end;
1919           while (last_trailing >= element + separator_len &&
1920                  strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1921             last_trailing -= separator_len;
1922
1923           if (!have_leading)
1924             {
1925               /* If the leading and trailing separator strings are in the
1926                * same element and overlap, the result is exactly that element
1927                */
1928               if (last_trailing <= start)
1929                 single_element = element;
1930                   
1931               g_string_append_len (result, element, start - element);
1932               have_leading = TRUE;
1933             }
1934           else
1935             single_element = NULL;
1936         }
1937
1938       if (end == start)
1939         continue;
1940
1941       if (!is_first)
1942         g_string_append (result, separator);
1943       
1944       g_string_append_len (result, start, end - start);
1945       is_first = FALSE;
1946     }
1947
1948   if (single_element)
1949     {
1950       g_string_free (result, TRUE);
1951       return g_strdup (single_element);
1952     }
1953   else
1954     {
1955       if (last_trailing)
1956         g_string_append (result, last_trailing);
1957   
1958       return g_string_free (result, FALSE);
1959     }
1960 }
1961
1962 /**
1963  * g_build_pathv:
1964  * @separator: a string used to separator the elements of the path.
1965  * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
1966  *     array of strings containing the path elements.
1967  * 
1968  * Behaves exactly like g_build_path(), but takes the path elements 
1969  * as a string array, instead of varargs. This function is mainly
1970  * meant for language bindings.
1971  *
1972  * Returns: (type filename) (transfer full): a newly-allocated string that
1973  *     must be freed with g_free().
1974  *
1975  * Since: 2.8
1976  */
1977 gchar *
1978 g_build_pathv (const gchar  *separator,
1979                gchar       **args)
1980 {
1981   if (!args)
1982     return NULL;
1983
1984   return g_build_path_va (separator, NULL, NULL, args);
1985 }
1986
1987
1988 /**
1989  * g_build_path:
1990  * @separator: (type filename): a string used to separator the elements of the path.
1991  * @first_element: (type filename): the first element in the path
1992  * @...: remaining elements in path, terminated by %NULL
1993  * 
1994  * Creates a path from a series of elements using @separator as the
1995  * separator between elements. At the boundary between two elements,
1996  * any trailing occurrences of separator in the first element, or
1997  * leading occurrences of separator in the second element are removed
1998  * and exactly one copy of the separator is inserted.
1999  *
2000  * Empty elements are ignored.
2001  *
2002  * The number of leading copies of the separator on the result is
2003  * the same as the number of leading copies of the separator on
2004  * the first non-empty element.
2005  *
2006  * The number of trailing copies of the separator on the result is
2007  * the same as the number of trailing copies of the separator on
2008  * the last non-empty element. (Determination of the number of
2009  * trailing copies is done without stripping leading copies, so
2010  * if the separator is `ABA`, then `ABABA` has 1 trailing copy.)
2011  *
2012  * However, if there is only a single non-empty element, and there
2013  * are no characters in that element not part of the leading or
2014  * trailing separators, then the result is exactly the original value
2015  * of that element.
2016  *
2017  * Other than for determination of the number of leading and trailing
2018  * copies of the separator, elements consisting only of copies
2019  * of the separator are ignored.
2020  *
2021  * Returns: (type filename) (transfer full): a newly-allocated string that
2022  *     must be freed with g_free().
2023  **/
2024 gchar *
2025 g_build_path (const gchar *separator,
2026               const gchar *first_element,
2027               ...)
2028 {
2029   gchar *str;
2030   va_list args;
2031
2032   g_return_val_if_fail (separator != NULL, NULL);
2033
2034   va_start (args, first_element);
2035   str = g_build_path_va (separator, first_element, &args, NULL);
2036   va_end (args);
2037
2038   return str;
2039 }
2040
2041 #ifdef G_OS_WIN32
2042
2043 static gchar *
2044 g_build_pathname_va (const gchar  *first_element,
2045                      va_list      *args,
2046                      gchar       **str_array)
2047 {
2048   /* Code copied from g_build_pathv(), and modified to use two
2049    * alternative single-character separators.
2050    */
2051   GString *result;
2052   gboolean is_first = TRUE;
2053   gboolean have_leading = FALSE;
2054   const gchar *single_element = NULL;
2055   const gchar *next_element;
2056   const gchar *last_trailing = NULL;
2057   gchar current_separator = '\\';
2058   gint i = 0;
2059
2060   result = g_string_new (NULL);
2061
2062   if (str_array)
2063     next_element = str_array[i++];
2064   else
2065     next_element = first_element;
2066   
2067   while (TRUE)
2068     {
2069       const gchar *element;
2070       const gchar *start;
2071       const gchar *end;
2072
2073       if (next_element)
2074         {
2075           element = next_element;
2076           if (str_array)
2077             next_element = str_array[i++];
2078           else
2079             next_element = va_arg (*args, gchar *);
2080         }
2081       else
2082         break;
2083
2084       /* Ignore empty elements */
2085       if (!*element)
2086         continue;
2087       
2088       start = element;
2089
2090       if (TRUE)
2091         {
2092           while (start &&
2093                  (*start == '\\' || *start == '/'))
2094             {
2095               current_separator = *start;
2096               start++;
2097             }
2098         }
2099
2100       end = start + strlen (start);
2101       
2102       if (TRUE)
2103         {
2104           while (end >= start + 1 &&
2105                  (end[-1] == '\\' || end[-1] == '/'))
2106             {
2107               current_separator = end[-1];
2108               end--;
2109             }
2110           
2111           last_trailing = end;
2112           while (last_trailing >= element + 1 &&
2113                  (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
2114             last_trailing--;
2115
2116           if (!have_leading)
2117             {
2118               /* If the leading and trailing separator strings are in the
2119                * same element and overlap, the result is exactly that element
2120                */
2121               if (last_trailing <= start)
2122                 single_element = element;
2123                   
2124               g_string_append_len (result, element, start - element);
2125               have_leading = TRUE;
2126             }
2127           else
2128             single_element = NULL;
2129         }
2130
2131       if (end == start)
2132         continue;
2133
2134       if (!is_first)
2135         g_string_append_len (result, &current_separator, 1);
2136       
2137       g_string_append_len (result, start, end - start);
2138       is_first = FALSE;
2139     }
2140
2141   if (single_element)
2142     {
2143       g_string_free (result, TRUE);
2144       return g_strdup (single_element);
2145     }
2146   else
2147     {
2148       if (last_trailing)
2149         g_string_append (result, last_trailing);
2150   
2151       return g_string_free (result, FALSE);
2152     }
2153 }
2154
2155 #endif
2156
2157 static gchar *
2158 g_build_filename_va (const gchar  *first_argument,
2159                      va_list      *args,
2160                      gchar       **str_array)
2161 {
2162   gchar *str;
2163
2164 #ifndef G_OS_WIN32
2165   str = g_build_path_va (G_DIR_SEPARATOR_S, first_argument, args, str_array);
2166 #else
2167   str = g_build_pathname_va (first_argument, args, str_array);
2168 #endif
2169
2170   return str;
2171 }
2172
2173 /**
2174  * g_build_filename_valist:
2175  * @first_element: (type filename): the first element in the path
2176  * @args: va_list of remaining elements in path
2177  *
2178  * Behaves exactly like g_build_filename(), but takes the path elements
2179  * as a va_list. This function is mainly meant for language bindings.
2180  *
2181  * Returns: (type filename) (transfer full): a newly-allocated string that
2182  *     must be freed with g_free().
2183  *
2184  * Since: 2.56
2185  */
2186 gchar *
2187 g_build_filename_valist (const gchar  *first_element,
2188                          va_list      *args)
2189 {
2190   g_return_val_if_fail (first_element != NULL, NULL);
2191
2192   return g_build_filename_va (first_element, args, NULL);
2193 }
2194
2195 /**
2196  * g_build_filenamev:
2197  * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
2198  *     array of strings containing the path elements.
2199  * 
2200  * Behaves exactly like g_build_filename(), but takes the path elements 
2201  * as a string array, instead of varargs. This function is mainly
2202  * meant for language bindings.
2203  *
2204  * Returns: (type filename) (transfer full): a newly-allocated string that
2205  *     must be freed with g_free().
2206  *
2207  * Since: 2.8
2208  */
2209 gchar *
2210 g_build_filenamev (gchar **args)
2211 {
2212   return g_build_filename_va (NULL, NULL, args);
2213 }
2214
2215 /**
2216  * g_build_filename:
2217  * @first_element: (type filename): the first element in the path
2218  * @...: remaining elements in path, terminated by %NULL
2219  * 
2220  * Creates a filename from a series of elements using the correct
2221  * separator for filenames.
2222  *
2223  * On Unix, this function behaves identically to `g_build_path
2224  * (G_DIR_SEPARATOR_S, first_element, ....)`.
2225  *
2226  * On Windows, it takes into account that either the backslash
2227  * (`\` or slash (`/`) can be used as separator in filenames, but
2228  * otherwise behaves as on UNIX. When file pathname separators need
2229  * to be inserted, the one that last previously occurred in the
2230  * parameters (reading from left to right) is used.
2231  *
2232  * No attempt is made to force the resulting filename to be an absolute
2233  * path. If the first element is a relative path, the result will
2234  * be a relative path.
2235  *
2236  * Returns: (type filename) (transfer full): a newly-allocated string that
2237  *     must be freed with g_free().
2238  **/
2239 gchar *
2240 g_build_filename (const gchar *first_element, 
2241                   ...)
2242 {
2243   gchar *str;
2244   va_list args;
2245
2246   va_start (args, first_element);
2247   str = g_build_filename_va (first_element, &args, NULL);
2248   va_end (args);
2249
2250   return str;
2251 }
2252
2253 /**
2254  * g_file_read_link:
2255  * @filename: (type filename): the symbolic link
2256  * @error: return location for a #GError
2257  *
2258  * Reads the contents of the symbolic link @filename like the POSIX
2259  * readlink() function.
2260  *
2261  * The returned string is in the encoding used
2262  * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
2263  *
2264  * The returned string may also be a relative path. Use g_build_filename() to
2265  * convert it to an absolute path:
2266  * |[
2267  * g_autoptr(GError) local_error = NULL;
2268  * g_autofree gchar *link_target = g_file_read_link ("/etc/localtime", &local_error);
2269  *
2270  * if (local_error != NULL)
2271  *   g_error ("Error reading link: %s", local_error->message);
2272  *
2273  * if (!g_path_is_absolute (link_target))
2274  *   {
2275  *     g_autofree gchar *absolute_link_target = g_build_filename ("/etc", link_target, NULL);
2276  *     g_free (link_target);
2277  *     link_target = g_steal_pointer (&absolute_link_target);
2278  *   }
2279  * ]|
2280  *
2281  * Returns: (type filename) (transfer full): A newly-allocated string with
2282  *     the contents of the symbolic link, or %NULL if an error occurred.
2283  *
2284  * Since: 2.4
2285  */
2286 gchar *
2287 g_file_read_link (const gchar  *filename,
2288                   GError      **error)
2289 {
2290 #if defined (HAVE_READLINK)
2291   gchar *buffer;
2292   size_t size;
2293   gssize read_size;
2294   
2295   g_return_val_if_fail (filename != NULL, NULL);
2296   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2297
2298   size = 256;
2299   buffer = g_malloc (size);
2300   
2301   while (TRUE) 
2302     {
2303       read_size = readlink (filename, buffer, size);
2304       if (read_size < 0)
2305         {
2306           int saved_errno = errno;
2307           if (error)
2308             set_file_error (error,
2309                             filename,
2310                             _("Failed to read the symbolic link “%s”: %s"),
2311                             saved_errno);
2312           g_free (buffer);
2313           return NULL;
2314         }
2315     
2316       if ((size_t) read_size < size)
2317         {
2318           buffer[read_size] = 0;
2319           return buffer;
2320         }
2321       
2322       size *= 2;
2323       buffer = g_realloc (buffer, size);
2324     }
2325 #elif defined (G_OS_WIN32)
2326   gchar *buffer;
2327   gssize read_size;
2328   
2329   g_return_val_if_fail (filename != NULL, NULL);
2330   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2331
2332   read_size = g_win32_readlink_utf8 (filename, NULL, 0, &buffer, TRUE);
2333   if (read_size < 0)
2334     {
2335       int saved_errno = errno;
2336       if (error)
2337         set_file_error (error,
2338                         filename,
2339                         _("Failed to read the symbolic link “%s”: %s"),
2340                         saved_errno);
2341       return NULL;
2342     }
2343   else if (read_size == 0)
2344     return strdup ("");
2345   else
2346     return buffer;
2347 #else
2348   g_return_val_if_fail (filename != NULL, NULL);
2349   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2350
2351   g_set_error_literal (error,
2352                        G_FILE_ERROR,
2353                        G_FILE_ERROR_INVAL,
2354                        _("Symbolic links not supported"));
2355         
2356   return NULL;
2357 #endif
2358 }
2359
2360 /**
2361  * g_path_is_absolute:
2362  * @file_name: (type filename): a file name
2363  *
2364  * Returns %TRUE if the given @file_name is an absolute file name.
2365  * Note that this is a somewhat vague concept on Windows.
2366  *
2367  * On POSIX systems, an absolute file name is well-defined. It always
2368  * starts from the single root directory. For example "/usr/local".
2369  *
2370  * On Windows, the concepts of current drive and drive-specific
2371  * current directory introduce vagueness. This function interprets as
2372  * an absolute file name one that either begins with a directory
2373  * separator such as "\Users\tml" or begins with the root on a drive,
2374  * for example "C:\Windows". The first case also includes UNC paths
2375  * such as "\\\\myserver\docs\foo". In all cases, either slashes or
2376  * backslashes are accepted.
2377  *
2378  * Note that a file name relative to the current drive root does not
2379  * truly specify a file uniquely over time and across processes, as
2380  * the current drive is a per-process value and can be changed.
2381  *
2382  * File names relative the current directory on some specific drive,
2383  * such as "D:foo/bar", are not interpreted as absolute by this
2384  * function, but they obviously are not relative to the normal current
2385  * directory as returned by getcwd() or g_get_current_dir()
2386  * either. Such paths should be avoided, or need to be handled using
2387  * Windows-specific code.
2388  *
2389  * Returns: %TRUE if @file_name is absolute
2390  */
2391 gboolean
2392 g_path_is_absolute (const gchar *file_name)
2393 {
2394   g_return_val_if_fail (file_name != NULL, FALSE);
2395
2396   if (G_IS_DIR_SEPARATOR (file_name[0]))
2397     return TRUE;
2398
2399 #ifdef G_OS_WIN32
2400   /* Recognize drive letter on native Windows */
2401   if (g_ascii_isalpha (file_name[0]) &&
2402       file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
2403     return TRUE;
2404 #endif
2405
2406   return FALSE;
2407 }
2408
2409 /**
2410  * g_path_skip_root:
2411  * @file_name: (type filename): a file name
2412  *
2413  * Returns a pointer into @file_name after the root component,
2414  * i.e. after the "/" in UNIX or "C:\" under Windows. If @file_name
2415  * is not an absolute path it returns %NULL.
2416  *
2417  * Returns: (type filename) (nullable): a pointer into @file_name after the
2418  *     root component
2419  */
2420 const gchar *
2421 g_path_skip_root (const gchar *file_name)
2422 {
2423   g_return_val_if_fail (file_name != NULL, NULL);
2424
2425 #ifdef G_PLATFORM_WIN32
2426   /* Skip \\server\share or //server/share */
2427   if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2428       G_IS_DIR_SEPARATOR (file_name[1]) &&
2429       file_name[2] &&
2430       !G_IS_DIR_SEPARATOR (file_name[2]))
2431     {
2432       gchar *p;
2433       p = strchr (file_name + 2, G_DIR_SEPARATOR);
2434
2435 #ifdef G_OS_WIN32
2436       {
2437         gchar *q;
2438
2439         q = strchr (file_name + 2, '/');
2440         if (p == NULL || (q != NULL && q < p))
2441         p = q;
2442       }
2443 #endif
2444
2445       if (p && p > file_name + 2 && p[1])
2446         {
2447           file_name = p + 1;
2448
2449           while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
2450             file_name++;
2451
2452           /* Possibly skip a backslash after the share name */
2453           if (G_IS_DIR_SEPARATOR (file_name[0]))
2454             file_name++;
2455
2456           return (gchar *)file_name;
2457         }
2458     }
2459 #endif
2460
2461   /* Skip initial slashes */
2462   if (G_IS_DIR_SEPARATOR (file_name[0]))
2463     {
2464       while (G_IS_DIR_SEPARATOR (file_name[0]))
2465         file_name++;
2466       return (gchar *)file_name;
2467     }
2468
2469 #ifdef G_OS_WIN32
2470   /* Skip X:\ */
2471   if (g_ascii_isalpha (file_name[0]) &&
2472       file_name[1] == ':' &&
2473       G_IS_DIR_SEPARATOR (file_name[2]))
2474     return (gchar *)file_name + 3;
2475 #endif
2476
2477   return NULL;
2478 }
2479
2480 /**
2481  * g_basename:
2482  * @file_name: (type filename): the name of the file
2483  *
2484  * Gets the name of the file without any leading directory
2485  * components. It returns a pointer into the given file name
2486  * string.
2487  *
2488  * Returns: (type filename): the name of the file without any leading
2489  *     directory components
2490  *
2491  * Deprecated:2.2: Use g_path_get_basename() instead, but notice
2492  *     that g_path_get_basename() allocates new memory for the
2493  *     returned string, unlike this function which returns a pointer
2494  *     into the argument.
2495  */
2496 const gchar *
2497 g_basename (const gchar *file_name)
2498 {
2499   gchar *base;
2500
2501   g_return_val_if_fail (file_name != NULL, NULL);
2502
2503   base = strrchr (file_name, G_DIR_SEPARATOR);
2504
2505 #ifdef G_OS_WIN32
2506   {
2507     gchar *q;
2508     q = strrchr (file_name, '/');
2509     if (base == NULL || (q != NULL && q > base))
2510       base = q;
2511   }
2512 #endif
2513
2514   if (base)
2515     return base + 1;
2516
2517 #ifdef G_OS_WIN32
2518   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2519     return (gchar*) file_name + 2;
2520 #endif
2521
2522   return (gchar*) file_name;
2523 }
2524
2525 /**
2526  * g_path_get_basename:
2527  * @file_name: (type filename): the name of the file
2528  *
2529  * Gets the last component of the filename.
2530  *
2531  * If @file_name ends with a directory separator it gets the component
2532  * before the last slash. If @file_name consists only of directory
2533  * separators (and on Windows, possibly a drive letter), a single
2534  * separator is returned. If @file_name is empty, it gets ".".
2535  *
2536  * Returns: (type filename) (transfer full): a newly allocated string
2537  *    containing the last component of the filename
2538  */
2539 gchar *
2540 g_path_get_basename (const gchar *file_name)
2541 {
2542   gssize base;
2543   gssize last_nonslash;
2544   gsize len;
2545   gchar *retval;
2546
2547   g_return_val_if_fail (file_name != NULL, NULL);
2548
2549   if (file_name[0] == '\0')
2550     return g_strdup (".");
2551
2552   last_nonslash = strlen (file_name) - 1;
2553
2554   while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
2555     last_nonslash--;
2556
2557   if (last_nonslash == -1)
2558     /* string only containing slashes */
2559     return g_strdup (G_DIR_SEPARATOR_S);
2560
2561 #ifdef G_OS_WIN32
2562   if (last_nonslash == 1 &&
2563       g_ascii_isalpha (file_name[0]) &&
2564       file_name[1] == ':')
2565     /* string only containing slashes and a drive */
2566     return g_strdup (G_DIR_SEPARATOR_S);
2567 #endif
2568   base = last_nonslash;
2569
2570   while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
2571     base--;
2572
2573 #ifdef G_OS_WIN32
2574   if (base == -1 &&
2575       g_ascii_isalpha (file_name[0]) &&
2576       file_name[1] == ':')
2577     base = 1;
2578 #endif /* G_OS_WIN32 */
2579
2580   len = last_nonslash - base;
2581   retval = g_malloc (len + 1);
2582   memcpy (retval, file_name + (base + 1), len);
2583   retval [len] = '\0';
2584
2585   return retval;
2586 }
2587
2588 /**
2589  * g_dirname:
2590  * @file_name: (type filename): the name of the file
2591  *
2592  * Gets the directory components of a file name.
2593  *
2594  * If the file name has no directory components "." is returned.
2595  * The returned string should be freed when no longer needed.
2596  *
2597  * Returns: (type filename) (transfer full): the directory components of the file
2598  *
2599  * Deprecated: use g_path_get_dirname() instead
2600  */
2601
2602 /**
2603  * g_path_get_dirname:
2604  * @file_name: (type filename): the name of the file
2605  *
2606  * Gets the directory components of a file name. For example, the directory
2607  * component of `/usr/bin/test` is `/usr/bin`. The directory component of `/`
2608  * is `/`.
2609  *
2610  * If the file name has no directory components "." is returned.
2611  * The returned string should be freed when no longer needed.
2612  *
2613  * Returns: (type filename) (transfer full): the directory components of the file
2614  */
2615 gchar *
2616 g_path_get_dirname (const gchar *file_name)
2617 {
2618   gchar *base;
2619   gsize len;
2620
2621   g_return_val_if_fail (file_name != NULL, NULL);
2622
2623   base = strrchr (file_name, G_DIR_SEPARATOR);
2624
2625 #ifdef G_OS_WIN32
2626   {
2627     gchar *q;
2628     q = strrchr (file_name, '/');
2629     if (base == NULL || (q != NULL && q > base))
2630       base = q;
2631   }
2632 #endif
2633
2634   if (!base)
2635     {
2636 #ifdef G_OS_WIN32
2637       if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2638         {
2639           gchar drive_colon_dot[4];
2640
2641           drive_colon_dot[0] = file_name[0];
2642           drive_colon_dot[1] = ':';
2643           drive_colon_dot[2] = '.';
2644           drive_colon_dot[3] = '\0';
2645
2646           return g_strdup (drive_colon_dot);
2647         }
2648 #endif
2649     return g_strdup (".");
2650     }
2651
2652   while (base > file_name && G_IS_DIR_SEPARATOR (*base))
2653     base--;
2654
2655 #ifdef G_OS_WIN32
2656   /* base points to the char before the last slash.
2657    *
2658    * In case file_name is the root of a drive (X:\) or a child of the
2659    * root of a drive (X:\foo), include the slash.
2660    *
2661    * In case file_name is the root share of an UNC path
2662    * (\\server\share), add a slash, returning \\server\share\ .
2663    *
2664    * In case file_name is a direct child of a share in an UNC path
2665    * (\\server\share\foo), include the slash after the share name,
2666    * returning \\server\share\ .
2667    */
2668   if (base == file_name + 1 &&
2669       g_ascii_isalpha (file_name[0]) &&
2670       file_name[1] == ':')
2671     base++;
2672   else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2673            G_IS_DIR_SEPARATOR (file_name[1]) &&
2674            file_name[2] &&
2675            !G_IS_DIR_SEPARATOR (file_name[2]) &&
2676            base >= file_name + 2)
2677     {
2678       const gchar *p = file_name + 2;
2679       while (*p && !G_IS_DIR_SEPARATOR (*p))
2680         p++;
2681       if (p == base + 1)
2682         {
2683           len = (guint) strlen (file_name) + 1;
2684           base = g_new (gchar, len + 1);
2685           strcpy (base, file_name);
2686           base[len-1] = G_DIR_SEPARATOR;
2687           base[len] = 0;
2688           return base;
2689         }
2690       if (G_IS_DIR_SEPARATOR (*p))
2691         {
2692           p++;
2693           while (*p && !G_IS_DIR_SEPARATOR (*p))
2694             p++;
2695           if (p == base + 1)
2696             base++;
2697         }
2698     }
2699 #endif
2700
2701   len = (guint) 1 + base - file_name;
2702   base = g_new (gchar, len + 1);
2703   memmove (base, file_name, len);
2704   base[len] = 0;
2705
2706   return base;
2707 }
2708
2709 /**
2710  * g_canonicalize_filename:
2711  * @filename: (type filename): the name of the file
2712  * @relative_to: (type filename) (nullable): the relative directory, or %NULL
2713  * to use the current working directory
2714  *
2715  * Gets the canonical file name from @filename. All triple slashes are turned into
2716  * single slashes, and all `..` and `.`s resolved against @relative_to.
2717  *
2718  * Symlinks are not followed, and the returned path is guaranteed to be absolute.
2719  *
2720  * If @filename is an absolute path, @relative_to is ignored. Otherwise,
2721  * @relative_to will be prepended to @filename to make it absolute. @relative_to
2722  * must be an absolute path, or %NULL. If @relative_to is %NULL, it'll fallback
2723  * to g_get_current_dir().
2724  *
2725  * This function never fails, and will canonicalize file paths even if they don't
2726  * exist.
2727  *
2728  * No file system I/O is done.
2729  *
2730  * Returns: (type filename) (transfer full): a newly allocated string with the
2731  * canonical file path
2732  * Since: 2.58
2733  */
2734 gchar *
2735 g_canonicalize_filename (const gchar *filename,
2736                          const gchar *relative_to)
2737 {
2738   gchar *canon, *input, *output, *after_root, *output_start;
2739
2740   g_return_val_if_fail (relative_to == NULL || g_path_is_absolute (relative_to), NULL);
2741
2742   if (!g_path_is_absolute (filename))
2743     {
2744       gchar *cwd_allocated = NULL;
2745       const gchar  *cwd;
2746
2747       if (relative_to != NULL)
2748         cwd = relative_to;
2749       else
2750         cwd = cwd_allocated = g_get_current_dir ();
2751
2752       canon = g_build_filename (cwd, filename, NULL);
2753       g_free (cwd_allocated);
2754     }
2755   else
2756     {
2757       canon = g_strdup (filename);
2758     }
2759
2760   after_root = (char *)g_path_skip_root (canon);
2761
2762   if (after_root == NULL)
2763     {
2764       /* This shouldn't really happen, as g_get_current_dir() should
2765          return an absolute pathname, but bug 573843 shows this is
2766          not always happening */
2767       g_free (canon);
2768       return g_build_filename (G_DIR_SEPARATOR_S, filename, NULL);
2769     }
2770
2771   /* Find the first dir separator and use the canonical dir separator. */
2772   for (output = after_root - 1;
2773        (output >= canon) && G_IS_DIR_SEPARATOR (*output);
2774        output--)
2775     *output = G_DIR_SEPARATOR;
2776
2777   /* 1 to re-increment after the final decrement above (so that output >= canon),
2778    * and 1 to skip the first `/`. There might not be a first `/` if
2779    * the @canon is a Windows `//server/share` style path with no
2780    * trailing directories. @after_root will be '\0' in that case. */
2781   output++;
2782   if (*output == G_DIR_SEPARATOR)
2783     output++;
2784
2785   /* POSIX allows double slashes at the start to mean something special
2786    * (as does windows too). So, "//" != "/", but more than two slashes
2787    * is treated as "/".
2788    */
2789   if (after_root - output == 1)
2790     output++;
2791
2792   input = after_root;
2793   output_start = output;
2794   while (*input)
2795     {
2796       /* input points to the next non-separator to be processed. */
2797       /* output points to the next location to write to. */
2798       g_assert (input > canon && G_IS_DIR_SEPARATOR (input[-1]));
2799       g_assert (output > canon && G_IS_DIR_SEPARATOR (output[-1]));
2800       g_assert (input >= output);
2801
2802       /* Ignore repeated dir separators. */
2803       while (G_IS_DIR_SEPARATOR (input[0]))
2804        input++;
2805
2806       /* Ignore single dot directory components. */
2807       if (input[0] == '.' && (input[1] == 0 || G_IS_DIR_SEPARATOR (input[1])))
2808         {
2809            if (input[1] == 0)
2810              break;
2811            input += 2;
2812         }
2813       /* Remove double-dot directory components along with the preceding
2814        * path component. */
2815       else if (input[0] == '.' && input[1] == '.' &&
2816                (input[2] == 0 || G_IS_DIR_SEPARATOR (input[2])))
2817         {
2818           if (output > output_start)
2819             {
2820               do
2821                 {
2822                   output--;
2823                 }
2824               while (!G_IS_DIR_SEPARATOR (output[-1]) && output > output_start);
2825             }
2826           if (input[2] == 0)
2827             break;
2828           input += 3;
2829         }
2830       /* Copy the input to the output until the next separator,
2831        * while converting it to canonical separator */
2832       else
2833         {
2834           while (*input && !G_IS_DIR_SEPARATOR (*input))
2835             *output++ = *input++;
2836           if (input[0] == 0)
2837             break;
2838           input++;
2839           *output++ = G_DIR_SEPARATOR;
2840         }
2841     }
2842
2843   /* Remove a potentially trailing dir separator */
2844   if (output > output_start && G_IS_DIR_SEPARATOR (output[-1]))
2845     output--;
2846
2847   *output = '\0';
2848
2849   return canon;
2850 }
2851
2852 #if defined(MAXPATHLEN)
2853 #define G_PATH_LENGTH MAXPATHLEN
2854 #elif defined(PATH_MAX)
2855 #define G_PATH_LENGTH PATH_MAX
2856 #elif defined(_PC_PATH_MAX)
2857 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
2858 #else
2859 #define G_PATH_LENGTH 2048
2860 #endif
2861
2862 /**
2863  * g_get_current_dir:
2864  *
2865  * Gets the current directory.
2866  *
2867  * The returned string should be freed when no longer needed.
2868  * The encoding of the returned string is system defined.
2869  * On Windows, it is always UTF-8.
2870  *
2871  * Since GLib 2.40, this function will return the value of the "PWD"
2872  * environment variable if it is set and it happens to be the same as
2873  * the current directory.  This can make a difference in the case that
2874  * the current directory is the target of a symbolic link.
2875  *
2876  * Returns: (type filename) (transfer full): the current directory
2877  */
2878 gchar *
2879 g_get_current_dir (void)
2880 {
2881 #ifdef G_OS_WIN32
2882
2883   gchar *dir = NULL;
2884   wchar_t dummy[2], *wdir;
2885   DWORD len;
2886
2887   len = GetCurrentDirectoryW (2, dummy);
2888   wdir = g_new (wchar_t, len);
2889
2890   if (GetCurrentDirectoryW (len, wdir) == len - 1)
2891     dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
2892
2893   g_free (wdir);
2894
2895   if (dir == NULL)
2896     dir = g_strdup ("\\");
2897
2898   return dir;
2899
2900 #else
2901   const gchar *pwd;
2902   gchar *buffer = NULL;
2903   gchar *dir = NULL;
2904   static gulong max_len = 0;
2905   struct stat pwdbuf, dotbuf;
2906
2907   pwd = g_getenv ("PWD");
2908   if (pwd != NULL &&
2909       g_stat (".", &dotbuf) == 0 && g_stat (pwd, &pwdbuf) == 0 &&
2910       dotbuf.st_dev == pwdbuf.st_dev && dotbuf.st_ino == pwdbuf.st_ino)
2911     return g_strdup (pwd);
2912
2913   if (max_len == 0)
2914     max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
2915
2916   while (max_len < G_MAXULONG / 2)
2917     {
2918       g_free (buffer);
2919       buffer = g_new (gchar, max_len + 1);
2920       *buffer = 0;
2921       dir = getcwd (buffer, max_len);
2922
2923       if (dir || errno != ERANGE)
2924         break;
2925
2926       max_len *= 2;
2927     }
2928
2929   if (!dir || !*buffer)
2930     {
2931       /* hm, should we g_error() out here?
2932        * this can happen if e.g. "./" has mode \0000
2933        */
2934       buffer[0] = G_DIR_SEPARATOR;
2935       buffer[1] = 0;
2936     }
2937
2938   dir = g_strdup (buffer);
2939   g_free (buffer);
2940
2941   return dir;
2942
2943 #endif /* !G_OS_WIN32 */
2944 }
2945
2946 #ifdef G_OS_WIN32
2947
2948 /* Binary compatibility versions. Not for newly compiled code. */
2949
2950 _GLIB_EXTERN gboolean g_file_test_utf8         (const gchar  *filename,
2951                                                 GFileTest     test);
2952 _GLIB_EXTERN gboolean g_file_get_contents_utf8 (const gchar  *filename,
2953                                                 gchar       **contents,
2954                                                 gsize        *length,
2955                                                 GError      **error);
2956 _GLIB_EXTERN gint     g_mkstemp_utf8           (gchar        *tmpl);
2957 _GLIB_EXTERN gint     g_file_open_tmp_utf8     (const gchar  *tmpl,
2958                                                 gchar       **name_used,
2959                                                 GError      **error);
2960 _GLIB_EXTERN gchar   *g_get_current_dir_utf8   (void);
2961
2962
2963 gboolean
2964 g_file_test_utf8 (const gchar *filename,
2965                   GFileTest    test)
2966 {
2967   return g_file_test (filename, test);
2968 }
2969
2970 gboolean
2971 g_file_get_contents_utf8 (const gchar  *filename,
2972                           gchar       **contents,
2973                           gsize        *length,
2974                           GError      **error)
2975 {
2976   return g_file_get_contents (filename, contents, length, error);
2977 }
2978
2979 gint
2980 g_mkstemp_utf8 (gchar *tmpl)
2981 {
2982   return g_mkstemp (tmpl);
2983 }
2984
2985 gint
2986 g_file_open_tmp_utf8 (const gchar  *tmpl,
2987                       gchar       **name_used,
2988                       GError      **error)
2989 {
2990   return g_file_open_tmp (tmpl, name_used, error);
2991 }
2992
2993 gchar *
2994 g_get_current_dir_utf8 (void)
2995 {
2996   return g_get_current_dir ();
2997 }
2998
2999 #endif