Partly revert "gio: Add filename type annotations"
[glib.git] / glib / gfileutils.c
blobdc1513fc3fda75e63f72aa22c6c5f016068c6a83
1 /* gfileutils.c - File utility functions
3 * Copyright 2000 Red Hat, Inc.
5 * GLib is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU Lesser General Public License as
7 * published by the Free Software Foundation; either version 2 of the
8 * License, or (at your option) any later version.
10 * GLib is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with GLib; see the file COPYING.LIB. If not,
17 * see <http://www.gnu.org/licenses/>.
20 #include "config.h"
21 #include "glibconfig.h"
23 #include <sys/stat.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <stdarg.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <fcntl.h>
32 #include <stdlib.h>
34 #ifdef G_OS_UNIX
35 #include <unistd.h>
36 #endif
37 #ifdef G_OS_WIN32
38 #include <windows.h>
39 #include <io.h>
40 #endif /* G_OS_WIN32 */
42 #ifndef S_ISLNK
43 #define S_ISLNK(x) 0
44 #endif
46 #ifndef O_BINARY
47 #define O_BINARY 0
48 #endif
50 #include "gfileutils.h"
52 #include "gstdio.h"
53 #include "glibintl.h"
55 #ifdef HAVE_LINUX_MAGIC_H /* for btrfs check */
56 #include <linux/magic.h>
57 #include <sys/vfs.h>
58 #endif
61 /**
62 * SECTION:fileutils
63 * @title: File Utilities
64 * @short_description: various file-related functions
66 * There is a group of functions which wrap the common POSIX functions
67 * dealing with filenames (g_open(), g_rename(), g_mkdir(), g_stat(),
68 * g_unlink(), g_remove(), g_fopen(), g_freopen()). The point of these
69 * wrappers is to make it possible to handle file names with any Unicode
70 * characters in them on Windows without having to use ifdefs and the
71 * wide character API in the application code.
73 * The pathname argument should be in the GLib file name encoding.
74 * On POSIX this is the actual on-disk encoding which might correspond
75 * to the locale settings of the process (or the `G_FILENAME_ENCODING`
76 * environment variable), or not.
78 * On Windows the GLib file name encoding is UTF-8. Note that the
79 * Microsoft C library does not use UTF-8, but has separate APIs for
80 * current system code page and wide characters (UTF-16). The GLib
81 * wrappers call the wide character API if present (on modern Windows
82 * systems), otherwise convert to/from the system code page.
84 * Another group of functions allows to open and read directories
85 * in the GLib file name encoding. These are g_dir_open(),
86 * g_dir_read_name(), g_dir_rewind(), g_dir_close().
89 /**
90 * GFileError:
91 * @G_FILE_ERROR_EXIST: Operation not permitted; only the owner of
92 * the file (or other resource) or processes with special privileges
93 * can perform the operation.
94 * @G_FILE_ERROR_ISDIR: File is a directory; you cannot open a directory
95 * for writing, or create or remove hard links to it.
96 * @G_FILE_ERROR_ACCES: Permission denied; the file permissions do not
97 * allow the attempted operation.
98 * @G_FILE_ERROR_NAMETOOLONG: Filename too long.
99 * @G_FILE_ERROR_NOENT: No such file or directory. This is a "file
100 * doesn't exist" error for ordinary files that are referenced in
101 * contexts where they are expected to already exist.
102 * @G_FILE_ERROR_NOTDIR: A file that isn't a directory was specified when
103 * a directory is required.
104 * @G_FILE_ERROR_NXIO: No such device or address. The system tried to
105 * use the device represented by a file you specified, and it
106 * couldn't find the device. This can mean that the device file was
107 * installed incorrectly, or that the physical device is missing or
108 * not correctly attached to the computer.
109 * @G_FILE_ERROR_NODEV: The underlying file system of the specified file
110 * does not support memory mapping.
111 * @G_FILE_ERROR_ROFS: The directory containing the new link can't be
112 * modified because it's on a read-only file system.
113 * @G_FILE_ERROR_TXTBSY: Text file busy.
114 * @G_FILE_ERROR_FAULT: You passed in a pointer to bad memory.
115 * (GLib won't reliably return this, don't pass in pointers to bad
116 * memory.)
117 * @G_FILE_ERROR_LOOP: Too many levels of symbolic links were encountered
118 * in looking up a file name. This often indicates a cycle of symbolic
119 * links.
120 * @G_FILE_ERROR_NOSPC: No space left on device; write operation on a
121 * file failed because the disk is full.
122 * @G_FILE_ERROR_NOMEM: No memory available. The system cannot allocate
123 * more virtual memory because its capacity is full.
124 * @G_FILE_ERROR_MFILE: The current process has too many files open and
125 * can't open any more. Duplicate descriptors do count toward this
126 * limit.
127 * @G_FILE_ERROR_NFILE: There are too many distinct file openings in the
128 * entire system.
129 * @G_FILE_ERROR_BADF: Bad file descriptor; for example, I/O on a
130 * descriptor that has been closed or reading from a descriptor open
131 * only for writing (or vice versa).
132 * @G_FILE_ERROR_INVAL: Invalid argument. This is used to indicate
133 * various kinds of problems with passing the wrong argument to a
134 * library function.
135 * @G_FILE_ERROR_PIPE: Broken pipe; there is no process reading from the
136 * other end of a pipe. Every library function that returns this
137 * error code also generates a 'SIGPIPE' signal; this signal
138 * terminates the program if not handled or blocked. Thus, your
139 * program will never actually see this code unless it has handled
140 * or blocked 'SIGPIPE'.
141 * @G_FILE_ERROR_AGAIN: Resource temporarily unavailable; the call might
142 * work if you try again later.
143 * @G_FILE_ERROR_INTR: Interrupted function call; an asynchronous signal
144 * occurred and prevented completion of the call. When this
145 * happens, you should try the call again.
146 * @G_FILE_ERROR_IO: Input/output error; usually used for physical read
147 * or write errors. i.e. the disk or other physical device hardware
148 * is returning errors.
149 * @G_FILE_ERROR_PERM: Operation not permitted; only the owner of the
150 * file (or other resource) or processes with special privileges can
151 * perform the operation.
152 * @G_FILE_ERROR_NOSYS: Function not implemented; this indicates that
153 * the system is missing some functionality.
154 * @G_FILE_ERROR_FAILED: Does not correspond to a UNIX error code; this
155 * is the standard "failed for unspecified reason" error code present
156 * in all #GError error code enumerations. Returned if no specific
157 * code applies.
159 * Values corresponding to @errno codes returned from file operations
160 * on UNIX. Unlike @errno codes, GFileError values are available on
161 * all systems, even Windows. The exact meaning of each code depends
162 * on what sort of file operation you were performing; the UNIX
163 * documentation gives more details. The following error code descriptions
164 * come from the GNU C Library manual, and are under the copyright
165 * of that manual.
167 * It's not very portable to make detailed assumptions about exactly
168 * which errors will be returned from a given operation. Some errors
169 * don't occur on some systems, etc., sometimes there are subtle
170 * differences in when a system will report a given error, etc.
174 * G_FILE_ERROR:
176 * Error domain for file operations. Errors in this domain will
177 * be from the #GFileError enumeration. See #GError for information
178 * on error domains.
182 * GFileTest:
183 * @G_FILE_TEST_IS_REGULAR: %TRUE if the file is a regular file
184 * (not a directory). Note that this test will also return %TRUE
185 * if the tested file is a symlink to a regular file.
186 * @G_FILE_TEST_IS_SYMLINK: %TRUE if the file is a symlink.
187 * @G_FILE_TEST_IS_DIR: %TRUE if the file is a directory.
188 * @G_FILE_TEST_IS_EXECUTABLE: %TRUE if the file is executable.
189 * @G_FILE_TEST_EXISTS: %TRUE if the file exists. It may or may not
190 * be a regular file.
192 * A test to perform on a file using g_file_test().
196 * g_mkdir_with_parents:
197 * @pathname: (type filename): a pathname in the GLib file name encoding
198 * @mode: permissions to use for newly created directories
200 * Create a directory if it doesn't already exist. Create intermediate
201 * parent directories as needed, too.
203 * Returns: 0 if the directory already exists, or was successfully
204 * created. Returns -1 if an error occurred, with errno set.
206 * Since: 2.8
209 g_mkdir_with_parents (const gchar *pathname,
210 int mode)
212 gchar *fn, *p;
214 if (pathname == NULL || *pathname == '\0')
216 errno = EINVAL;
217 return -1;
220 fn = g_strdup (pathname);
222 if (g_path_is_absolute (fn))
223 p = (gchar *) g_path_skip_root (fn);
224 else
225 p = fn;
229 while (*p && !G_IS_DIR_SEPARATOR (*p))
230 p++;
232 if (!*p)
233 p = NULL;
234 else
235 *p = '\0';
237 if (!g_file_test (fn, G_FILE_TEST_EXISTS))
239 if (g_mkdir (fn, mode) == -1 && errno != EEXIST)
241 int errno_save = errno;
242 g_free (fn);
243 errno = errno_save;
244 return -1;
247 else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
249 g_free (fn);
250 errno = ENOTDIR;
251 return -1;
253 if (p)
255 *p++ = G_DIR_SEPARATOR;
256 while (*p && G_IS_DIR_SEPARATOR (*p))
257 p++;
260 while (p);
262 g_free (fn);
264 return 0;
268 * g_file_test:
269 * @filename: (type filename): a filename to test in the
270 * GLib file name encoding
271 * @test: bitfield of #GFileTest flags
273 * Returns %TRUE if any of the tests in the bitfield @test are
274 * %TRUE. For example, `(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)`
275 * will return %TRUE if the file exists; the check whether it's a
276 * directory doesn't matter since the existence test is %TRUE. With
277 * the current set of available tests, there's no point passing in
278 * more than one test at a time.
280 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
281 * so for a symbolic link to a regular file g_file_test() will return
282 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
284 * Note, that for a dangling symbolic link g_file_test() will return
285 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
287 * You should never use g_file_test() to test whether it is safe
288 * to perform an operation, because there is always the possibility
289 * of the condition changing before you actually perform the operation.
290 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
291 * to know whether it is safe to write to a file without being
292 * tricked into writing into a different location. It doesn't work!
293 * |[<!-- language="C" -->
294 * // DON'T DO THIS
295 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
297 * fd = g_open (filename, O_WRONLY);
298 * // write to fd
300 * ]|
302 * Another thing to note is that %G_FILE_TEST_EXISTS and
303 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
304 * system call. This usually doesn't matter, but if your program
305 * is setuid or setgid it means that these tests will give you
306 * the answer for the real user ID and group ID, rather than the
307 * effective user ID and group ID.
309 * On Windows, there are no symlinks, so testing for
310 * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
311 * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
312 * its name indicates that it is executable, checking for well-known
313 * extensions and those listed in the `PATHEXT` environment variable.
315 * Returns: whether a test was %TRUE
317 gboolean
318 g_file_test (const gchar *filename,
319 GFileTest test)
321 #ifdef G_OS_WIN32
322 /* stuff missing in std vc6 api */
323 # ifndef INVALID_FILE_ATTRIBUTES
324 # define INVALID_FILE_ATTRIBUTES -1
325 # endif
326 # ifndef FILE_ATTRIBUTE_DEVICE
327 # define FILE_ATTRIBUTE_DEVICE 64
328 # endif
329 int attributes;
330 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
332 if (wfilename == NULL)
333 return FALSE;
335 attributes = GetFileAttributesW (wfilename);
337 g_free (wfilename);
339 if (attributes == INVALID_FILE_ATTRIBUTES)
340 return FALSE;
342 if (test & G_FILE_TEST_EXISTS)
343 return TRUE;
345 if (test & G_FILE_TEST_IS_REGULAR)
347 if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0)
348 return TRUE;
351 if (test & G_FILE_TEST_IS_DIR)
353 if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
354 return TRUE;
357 /* "while" so that we can exit this "loop" with a simple "break" */
358 while (test & G_FILE_TEST_IS_EXECUTABLE)
360 const gchar *lastdot = strrchr (filename, '.');
361 const gchar *pathext = NULL, *p;
362 int extlen;
364 if (lastdot == NULL)
365 break;
367 if (_stricmp (lastdot, ".exe") == 0 ||
368 _stricmp (lastdot, ".cmd") == 0 ||
369 _stricmp (lastdot, ".bat") == 0 ||
370 _stricmp (lastdot, ".com") == 0)
371 return TRUE;
373 /* Check if it is one of the types listed in %PATHEXT% */
375 pathext = g_getenv ("PATHEXT");
376 if (pathext == NULL)
377 break;
379 pathext = g_utf8_casefold (pathext, -1);
381 lastdot = g_utf8_casefold (lastdot, -1);
382 extlen = strlen (lastdot);
384 p = pathext;
385 while (TRUE)
387 const gchar *q = strchr (p, ';');
388 if (q == NULL)
389 q = p + strlen (p);
390 if (extlen == q - p &&
391 memcmp (lastdot, p, extlen) == 0)
393 g_free ((gchar *) pathext);
394 g_free ((gchar *) lastdot);
395 return TRUE;
397 if (*q)
398 p = q + 1;
399 else
400 break;
403 g_free ((gchar *) pathext);
404 g_free ((gchar *) lastdot);
405 break;
408 return FALSE;
409 #else
410 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
411 return TRUE;
413 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
415 if (getuid () != 0)
416 return TRUE;
418 /* For root, on some POSIX systems, access (filename, X_OK)
419 * will succeed even if no executable bits are set on the
420 * file. We fall through to a stat test to avoid that.
423 else
424 test &= ~G_FILE_TEST_IS_EXECUTABLE;
426 if (test & G_FILE_TEST_IS_SYMLINK)
428 struct stat s;
430 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
431 return TRUE;
434 if (test & (G_FILE_TEST_IS_REGULAR |
435 G_FILE_TEST_IS_DIR |
436 G_FILE_TEST_IS_EXECUTABLE))
438 struct stat s;
440 if (stat (filename, &s) == 0)
442 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
443 return TRUE;
445 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
446 return TRUE;
448 /* The extra test for root when access (file, X_OK) succeeds.
450 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
451 ((s.st_mode & S_IXOTH) ||
452 (s.st_mode & S_IXUSR) ||
453 (s.st_mode & S_IXGRP)))
454 return TRUE;
458 return FALSE;
459 #endif
462 G_DEFINE_QUARK (g-file-error-quark, g_file_error)
465 * g_file_error_from_errno:
466 * @err_no: an "errno" value
468 * Gets a #GFileError constant based on the passed-in @err_no.
469 * For example, if you pass in `EEXIST` this function returns
470 * #G_FILE_ERROR_EXIST. Unlike `errno` values, you can portably
471 * assume that all #GFileError values will exist.
473 * Normally a #GFileError value goes into a #GError returned
474 * from a function that manipulates files. So you would use
475 * g_file_error_from_errno() when constructing a #GError.
477 * Returns: #GFileError corresponding to the given @errno
479 GFileError
480 g_file_error_from_errno (gint err_no)
482 switch (err_no)
484 #ifdef EEXIST
485 case EEXIST:
486 return G_FILE_ERROR_EXIST;
487 #endif
489 #ifdef EISDIR
490 case EISDIR:
491 return G_FILE_ERROR_ISDIR;
492 #endif
494 #ifdef EACCES
495 case EACCES:
496 return G_FILE_ERROR_ACCES;
497 #endif
499 #ifdef ENAMETOOLONG
500 case ENAMETOOLONG:
501 return G_FILE_ERROR_NAMETOOLONG;
502 #endif
504 #ifdef ENOENT
505 case ENOENT:
506 return G_FILE_ERROR_NOENT;
507 #endif
509 #ifdef ENOTDIR
510 case ENOTDIR:
511 return G_FILE_ERROR_NOTDIR;
512 #endif
514 #ifdef ENXIO
515 case ENXIO:
516 return G_FILE_ERROR_NXIO;
517 #endif
519 #ifdef ENODEV
520 case ENODEV:
521 return G_FILE_ERROR_NODEV;
522 #endif
524 #ifdef EROFS
525 case EROFS:
526 return G_FILE_ERROR_ROFS;
527 #endif
529 #ifdef ETXTBSY
530 case ETXTBSY:
531 return G_FILE_ERROR_TXTBSY;
532 #endif
534 #ifdef EFAULT
535 case EFAULT:
536 return G_FILE_ERROR_FAULT;
537 #endif
539 #ifdef ELOOP
540 case ELOOP:
541 return G_FILE_ERROR_LOOP;
542 #endif
544 #ifdef ENOSPC
545 case ENOSPC:
546 return G_FILE_ERROR_NOSPC;
547 #endif
549 #ifdef ENOMEM
550 case ENOMEM:
551 return G_FILE_ERROR_NOMEM;
552 #endif
554 #ifdef EMFILE
555 case EMFILE:
556 return G_FILE_ERROR_MFILE;
557 #endif
559 #ifdef ENFILE
560 case ENFILE:
561 return G_FILE_ERROR_NFILE;
562 #endif
564 #ifdef EBADF
565 case EBADF:
566 return G_FILE_ERROR_BADF;
567 #endif
569 #ifdef EINVAL
570 case EINVAL:
571 return G_FILE_ERROR_INVAL;
572 #endif
574 #ifdef EPIPE
575 case EPIPE:
576 return G_FILE_ERROR_PIPE;
577 #endif
579 #ifdef EAGAIN
580 case EAGAIN:
581 return G_FILE_ERROR_AGAIN;
582 #endif
584 #ifdef EINTR
585 case EINTR:
586 return G_FILE_ERROR_INTR;
587 #endif
589 #ifdef EIO
590 case EIO:
591 return G_FILE_ERROR_IO;
592 #endif
594 #ifdef EPERM
595 case EPERM:
596 return G_FILE_ERROR_PERM;
597 #endif
599 #ifdef ENOSYS
600 case ENOSYS:
601 return G_FILE_ERROR_NOSYS;
602 #endif
604 default:
605 return G_FILE_ERROR_FAILED;
609 static char *
610 format_error_message (const gchar *filename,
611 const gchar *format_string,
612 int saved_errno) G_GNUC_FORMAT(2);
614 #pragma GCC diagnostic push
615 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
617 static char *
618 format_error_message (const gchar *filename,
619 const gchar *format_string,
620 int saved_errno)
622 gchar *display_name;
623 gchar *msg;
625 display_name = g_filename_display_name (filename);
626 msg = g_strdup_printf (format_string, display_name, g_strerror (saved_errno));
627 g_free (display_name);
629 return msg;
632 #pragma GCC diagnostic pop
634 /* format string must have two '%s':
636 * - the place for the filename
637 * - the place for the strerror
639 static void
640 set_file_error (GError **error,
641 const gchar *filename,
642 const gchar *format_string,
643 int saved_errno)
645 char *msg = format_error_message (filename, format_string, saved_errno);
647 g_set_error_literal (error, G_FILE_ERROR, g_file_error_from_errno (saved_errno),
648 msg);
649 g_free (msg);
652 static gboolean
653 get_contents_stdio (const gchar *filename,
654 FILE *f,
655 gchar **contents,
656 gsize *length,
657 GError **error)
659 gchar buf[4096];
660 gsize bytes; /* always <= sizeof(buf) */
661 gchar *str = NULL;
662 gsize total_bytes = 0;
663 gsize total_allocated = 0;
664 gchar *tmp;
665 gchar *display_filename;
667 g_assert (f != NULL);
669 while (!feof (f))
671 gint save_errno;
673 bytes = fread (buf, 1, sizeof (buf), f);
674 save_errno = errno;
676 if (total_bytes > G_MAXSIZE - bytes)
677 goto file_too_large;
679 /* Possibility of overflow eliminated above. */
680 while (total_bytes + bytes >= total_allocated)
682 if (str)
684 if (total_allocated > G_MAXSIZE / 2)
685 goto file_too_large;
686 total_allocated *= 2;
688 else
690 total_allocated = MIN (bytes + 1, sizeof (buf));
693 tmp = g_try_realloc (str, total_allocated);
695 if (tmp == NULL)
697 display_filename = g_filename_display_name (filename);
698 g_set_error (error,
699 G_FILE_ERROR,
700 G_FILE_ERROR_NOMEM,
701 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),
702 (gulong) total_allocated,
703 display_filename);
704 g_free (display_filename);
706 goto error;
709 str = tmp;
712 if (ferror (f))
714 display_filename = g_filename_display_name (filename);
715 g_set_error (error,
716 G_FILE_ERROR,
717 g_file_error_from_errno (save_errno),
718 _("Error reading file '%s': %s"),
719 display_filename,
720 g_strerror (save_errno));
721 g_free (display_filename);
723 goto error;
726 g_assert (str != NULL);
727 memcpy (str + total_bytes, buf, bytes);
729 total_bytes += bytes;
732 fclose (f);
734 if (total_allocated == 0)
736 str = g_new (gchar, 1);
737 total_bytes = 0;
740 str[total_bytes] = '\0';
742 if (length)
743 *length = total_bytes;
745 *contents = str;
747 return TRUE;
749 file_too_large:
750 display_filename = g_filename_display_name (filename);
751 g_set_error (error,
752 G_FILE_ERROR,
753 G_FILE_ERROR_FAILED,
754 _("File \"%s\" is too large"),
755 display_filename);
756 g_free (display_filename);
758 error:
760 g_free (str);
761 fclose (f);
763 return FALSE;
766 #ifndef G_OS_WIN32
768 static gboolean
769 get_contents_regfile (const gchar *filename,
770 struct stat *stat_buf,
771 gint fd,
772 gchar **contents,
773 gsize *length,
774 GError **error)
776 gchar *buf;
777 gsize bytes_read;
778 gsize size;
779 gsize alloc_size;
780 gchar *display_filename;
782 size = stat_buf->st_size;
784 alloc_size = size + 1;
785 buf = g_try_malloc (alloc_size);
787 if (buf == NULL)
789 display_filename = g_filename_display_name (filename);
790 g_set_error (error,
791 G_FILE_ERROR,
792 G_FILE_ERROR_NOMEM,
793 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),
794 (gulong) alloc_size,
795 display_filename);
796 g_free (display_filename);
797 goto error;
800 bytes_read = 0;
801 while (bytes_read < size)
803 gssize rc;
805 rc = read (fd, buf + bytes_read, size - bytes_read);
807 if (rc < 0)
809 if (errno != EINTR)
811 int save_errno = errno;
813 g_free (buf);
814 display_filename = g_filename_display_name (filename);
815 g_set_error (error,
816 G_FILE_ERROR,
817 g_file_error_from_errno (save_errno),
818 _("Failed to read from file '%s': %s"),
819 display_filename,
820 g_strerror (save_errno));
821 g_free (display_filename);
822 goto error;
825 else if (rc == 0)
826 break;
827 else
828 bytes_read += rc;
831 buf[bytes_read] = '\0';
833 if (length)
834 *length = bytes_read;
836 *contents = buf;
838 close (fd);
840 return TRUE;
842 error:
844 close (fd);
846 return FALSE;
849 static gboolean
850 get_contents_posix (const gchar *filename,
851 gchar **contents,
852 gsize *length,
853 GError **error)
855 struct stat stat_buf;
856 gint fd;
858 /* O_BINARY useful on Cygwin */
859 fd = open (filename, O_RDONLY|O_BINARY);
861 if (fd < 0)
863 int saved_errno = errno;
864 set_file_error (error,
865 filename,
866 _("Failed to open file '%s': %s"),
867 saved_errno);
869 return FALSE;
872 /* I don't think this will ever fail, aside from ENOMEM, but. */
873 if (fstat (fd, &stat_buf) < 0)
875 int saved_errno = errno;
876 set_file_error (error,
877 filename,
878 _("Failed to get attributes of file '%s': fstat() failed: %s"),
879 saved_errno);
880 close (fd);
882 return FALSE;
885 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
887 gboolean retval = get_contents_regfile (filename,
888 &stat_buf,
890 contents,
891 length,
892 error);
894 return retval;
896 else
898 FILE *f;
899 gboolean retval;
901 f = fdopen (fd, "r");
903 if (f == NULL)
905 int saved_errno = errno;
906 set_file_error (error,
907 filename,
908 _("Failed to open file '%s': fdopen() failed: %s"),
909 saved_errno);
911 return FALSE;
914 retval = get_contents_stdio (filename, f, contents, length, error);
916 return retval;
920 #else /* G_OS_WIN32 */
922 static gboolean
923 get_contents_win32 (const gchar *filename,
924 gchar **contents,
925 gsize *length,
926 GError **error)
928 FILE *f;
929 gboolean retval;
931 f = g_fopen (filename, "rb");
933 if (f == NULL)
935 int saved_errno = errno;
936 set_file_error (error,
937 filename,
938 _("Failed to open file '%s': %s"),
939 saved_errno);
941 return FALSE;
944 retval = get_contents_stdio (filename, f, contents, length, error);
946 return retval;
949 #endif
952 * g_file_get_contents:
953 * @filename: (type filename): name of a file to read contents from, in the GLib file name encoding
954 * @contents: (out) (array length=length) (element-type guint8): location to store an allocated string, use g_free() to free
955 * the returned string
956 * @length: (allow-none): location to store length in bytes of the contents, or %NULL
957 * @error: return location for a #GError, or %NULL
959 * Reads an entire file into allocated memory, with good error
960 * checking.
962 * If the call was successful, it returns %TRUE and sets @contents to the file
963 * contents and @length to the length of the file contents in bytes. The string
964 * stored in @contents will be nul-terminated, so for text files you can pass
965 * %NULL for the @length argument. If the call was not successful, it returns
966 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
967 * codes are those in the #GFileError enumeration. In the error case,
968 * @contents is set to %NULL and @length is set to zero.
970 * Returns: %TRUE on success, %FALSE if an error occurred
972 gboolean
973 g_file_get_contents (const gchar *filename,
974 gchar **contents,
975 gsize *length,
976 GError **error)
978 g_return_val_if_fail (filename != NULL, FALSE);
979 g_return_val_if_fail (contents != NULL, FALSE);
981 *contents = NULL;
982 if (length)
983 *length = 0;
985 #ifdef G_OS_WIN32
986 return get_contents_win32 (filename, contents, length, error);
987 #else
988 return get_contents_posix (filename, contents, length, error);
989 #endif
992 static gboolean
993 rename_file (const char *old_name,
994 const char *new_name,
995 GError **err)
997 errno = 0;
998 if (g_rename (old_name, new_name) == -1)
1000 int save_errno = errno;
1001 gchar *display_old_name = g_filename_display_name (old_name);
1002 gchar *display_new_name = g_filename_display_name (new_name);
1004 g_set_error (err,
1005 G_FILE_ERROR,
1006 g_file_error_from_errno (save_errno),
1007 _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
1008 display_old_name,
1009 display_new_name,
1010 g_strerror (save_errno));
1012 g_free (display_old_name);
1013 g_free (display_new_name);
1015 return FALSE;
1018 return TRUE;
1021 static gchar *
1022 write_to_temp_file (const gchar *contents,
1023 gssize length,
1024 const gchar *dest_file,
1025 GError **err)
1027 gchar *tmp_name;
1028 gchar *retval;
1029 gint fd;
1031 retval = NULL;
1033 tmp_name = g_strdup_printf ("%s.XXXXXX", dest_file);
1035 errno = 0;
1036 fd = g_mkstemp_full (tmp_name, O_RDWR | O_BINARY, 0666);
1038 if (fd == -1)
1040 int saved_errno = errno;
1041 set_file_error (err,
1042 tmp_name, _("Failed to create file '%s': %s"),
1043 saved_errno);
1044 goto out;
1047 #ifdef HAVE_FALLOCATE
1048 if (length > 0)
1050 /* We do this on a 'best effort' basis... It may not be supported
1051 * on the underlying filesystem.
1053 (void) fallocate (fd, 0, 0, length);
1055 #endif
1056 while (length > 0)
1058 gssize s;
1060 s = write (fd, contents, length);
1062 if (s < 0)
1064 int saved_errno = errno;
1065 if (saved_errno == EINTR)
1066 continue;
1068 set_file_error (err,
1069 tmp_name, _("Failed to write file '%s': write() failed: %s"),
1070 saved_errno);
1071 close (fd);
1072 g_unlink (tmp_name);
1074 goto out;
1077 g_assert (s <= length);
1079 contents += s;
1080 length -= s;
1083 #ifdef BTRFS_SUPER_MAGIC
1085 struct statfs buf;
1087 /* On Linux, on btrfs, skip the fsync since rename-over-existing is
1088 * guaranteed to be atomic and this is the only case in which we
1089 * would fsync() anyway.
1092 if (fstatfs (fd, &buf) == 0 && buf.f_type == BTRFS_SUPER_MAGIC)
1093 goto no_fsync;
1095 #endif
1097 #ifdef HAVE_FSYNC
1099 struct stat statbuf;
1101 errno = 0;
1102 /* If the final destination exists and is > 0 bytes, we want to sync the
1103 * newly written file to ensure the data is on disk when we rename over
1104 * the destination. Otherwise if we get a system crash we can lose both
1105 * the new and the old file on some filesystems. (I.E. those that don't
1106 * guarantee the data is written to the disk before the metadata.)
1108 if (g_lstat (dest_file, &statbuf) == 0 && statbuf.st_size > 0 && fsync (fd) != 0)
1110 int saved_errno = errno;
1111 set_file_error (err,
1112 tmp_name, _("Failed to write file '%s': fsync() failed: %s"),
1113 saved_errno);
1114 close (fd);
1115 g_unlink (tmp_name);
1117 goto out;
1120 #endif
1122 #ifdef BTRFS_SUPER_MAGIC
1123 no_fsync:
1124 #endif
1126 errno = 0;
1127 if (!g_close (fd, err))
1129 g_unlink (tmp_name);
1131 goto out;
1134 retval = g_strdup (tmp_name);
1136 out:
1137 g_free (tmp_name);
1139 return retval;
1143 * g_file_set_contents:
1144 * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1145 * encoding
1146 * @contents: (array length=length) (element-type guint8): string to write to the file
1147 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1148 * @error: return location for a #GError, or %NULL
1150 * Writes all of @contents to a file named @filename, with good error checking.
1151 * If a file called @filename already exists it will be overwritten.
1153 * This write is atomic in the sense that it is first written to a temporary
1154 * file which is then renamed to the final name. Notes:
1156 * - On UNIX, if @filename already exists hard links to @filename will break.
1157 * Also since the file is recreated, existing permissions, access control
1158 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1159 * the link itself will be replaced, not the linked file.
1161 * - On Windows renaming a file will not remove an existing file with the
1162 * new name, so on Windows there is a race condition between the existing
1163 * file being removed and the temporary file being renamed.
1165 * - On Windows there is no way to remove a file that is open to some
1166 * process, or mapped into memory. Thus, this function will fail if
1167 * @filename already exists and is open.
1169 * If the call was successful, it returns %TRUE. If the call was not successful,
1170 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1171 * Possible error codes are those in the #GFileError enumeration.
1173 * Note that the name for the temporary file is constructed by appending up
1174 * to 7 characters to @filename.
1176 * Returns: %TRUE on success, %FALSE if an error occurred
1178 * Since: 2.8
1180 gboolean
1181 g_file_set_contents (const gchar *filename,
1182 const gchar *contents,
1183 gssize length,
1184 GError **error)
1186 gchar *tmp_filename;
1187 gboolean retval;
1188 GError *rename_error = NULL;
1190 g_return_val_if_fail (filename != NULL, FALSE);
1191 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1192 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1193 g_return_val_if_fail (length >= -1, FALSE);
1195 if (length == -1)
1196 length = strlen (contents);
1198 tmp_filename = write_to_temp_file (contents, length, filename, error);
1200 if (!tmp_filename)
1202 retval = FALSE;
1203 goto out;
1206 if (!rename_file (tmp_filename, filename, &rename_error))
1208 #ifndef G_OS_WIN32
1210 g_unlink (tmp_filename);
1211 g_propagate_error (error, rename_error);
1212 retval = FALSE;
1213 goto out;
1215 #else /* G_OS_WIN32 */
1217 /* Renaming failed, but on Windows this may just mean
1218 * the file already exists. So if the target file
1219 * exists, try deleting it and do the rename again.
1221 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1223 g_unlink (tmp_filename);
1224 g_propagate_error (error, rename_error);
1225 retval = FALSE;
1226 goto out;
1229 g_error_free (rename_error);
1231 if (g_unlink (filename) == -1)
1233 int saved_errno = errno;
1234 set_file_error (error,
1235 filename,
1236 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1237 saved_errno);
1238 g_unlink (tmp_filename);
1239 retval = FALSE;
1240 goto out;
1243 if (!rename_file (tmp_filename, filename, error))
1245 g_unlink (tmp_filename);
1246 retval = FALSE;
1247 goto out;
1250 #endif
1253 retval = TRUE;
1255 out:
1256 g_free (tmp_filename);
1257 return retval;
1261 * get_tmp_file based on the mkstemp implementation from the GNU C library.
1262 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1264 typedef gint (*GTmpFileCallback) (const gchar *, gint, gint);
1266 static gint
1267 get_tmp_file (gchar *tmpl,
1268 GTmpFileCallback f,
1269 int flags,
1270 int mode)
1272 char *XXXXXX;
1273 int count, fd;
1274 static const char letters[] =
1275 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1276 static const int NLETTERS = sizeof (letters) - 1;
1277 glong value;
1278 GTimeVal tv;
1279 static int counter = 0;
1281 g_return_val_if_fail (tmpl != NULL, -1);
1283 /* find the last occurrence of "XXXXXX" */
1284 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1286 if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1288 errno = EINVAL;
1289 return -1;
1292 /* Get some more or less random data. */
1293 g_get_current_time (&tv);
1294 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1296 for (count = 0; count < 100; value += 7777, ++count)
1298 glong v = value;
1300 /* Fill in the random bits. */
1301 XXXXXX[0] = letters[v % NLETTERS];
1302 v /= NLETTERS;
1303 XXXXXX[1] = letters[v % NLETTERS];
1304 v /= NLETTERS;
1305 XXXXXX[2] = letters[v % NLETTERS];
1306 v /= NLETTERS;
1307 XXXXXX[3] = letters[v % NLETTERS];
1308 v /= NLETTERS;
1309 XXXXXX[4] = letters[v % NLETTERS];
1310 v /= NLETTERS;
1311 XXXXXX[5] = letters[v % NLETTERS];
1313 fd = f (tmpl, flags, mode);
1315 if (fd >= 0)
1316 return fd;
1317 else if (errno != EEXIST)
1318 /* Any other error will apply also to other names we might
1319 * try, and there are 2^32 or so of them, so give up now.
1321 return -1;
1324 /* We got out of the loop because we ran out of combinations to try. */
1325 errno = EEXIST;
1326 return -1;
1329 /* Some GTmpFileCallback implementations.
1331 * Note: we cannot use open() or g_open() directly because even though
1332 * they appear compatible, they may be vararg functions and calling
1333 * varargs functions through a non-varargs type is undefined.
1335 static gint
1336 wrap_g_mkdir (const gchar *filename,
1337 int flags G_GNUC_UNUSED,
1338 int mode)
1340 /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1341 return g_mkdir (filename, mode);
1344 static gint
1345 wrap_g_open (const gchar *filename,
1346 int flags,
1347 int mode)
1349 return g_open (filename, flags, mode);
1353 * g_mkdtemp_full:
1354 * @tmpl: (type filename): template directory name
1355 * @mode: permissions to create the temporary directory with
1357 * Creates a temporary directory. See the mkdtemp() documentation
1358 * on most UNIX-like systems.
1360 * The parameter is a string that should follow the rules for
1361 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1362 * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1363 * sequence does not have to occur at the very end of the template
1364 * and you can pass a @mode. The X string will be modified to form
1365 * the name of a directory that didn't exist. The string should be
1366 * in the GLib file name encoding. Most importantly, on Windows it
1367 * should be in UTF-8.
1369 * Returns: (type filename): A pointer to @tmpl, which has been modified
1370 * to hold the directory name. In case of errors, %NULL is
1371 * returned, and %errno will be set.
1373 * Since: 2.30
1375 gchar *
1376 g_mkdtemp_full (gchar *tmpl,
1377 gint mode)
1379 if (get_tmp_file (tmpl, wrap_g_mkdir, 0, mode) == -1)
1380 return NULL;
1381 else
1382 return tmpl;
1386 * g_mkdtemp:
1387 * @tmpl: (type filename): template directory name
1389 * Creates a temporary directory. See the mkdtemp() documentation
1390 * on most UNIX-like systems.
1392 * The parameter is a string that should follow the rules for
1393 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1394 * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1395 * sequence does not have to occur at the very end of the template
1396 * and you can pass a @mode and additional @flags. The X string will
1397 * be modified to form the name of a directory that didn't exist.
1398 * The string should be in the GLib file name encoding. Most importantly,
1399 * on Windows it should be in UTF-8.
1401 * Returns: (type filename): A pointer to @tmpl, which has been modified
1402 * to hold the directory name. In case of errors, %NULL is
1403 * returned and %errno will be set.
1405 * Since: 2.30
1407 gchar *
1408 g_mkdtemp (gchar *tmpl)
1410 return g_mkdtemp_full (tmpl, 0700);
1414 * g_mkstemp_full:
1415 * @tmpl: (type filename): template filename
1416 * @flags: flags to pass to an open() call in addition to O_EXCL
1417 * and O_CREAT, which are passed automatically
1418 * @mode: permissions to create the temporary file with
1420 * Opens a temporary file. See the mkstemp() documentation
1421 * on most UNIX-like systems.
1423 * The parameter is a string that should follow the rules for
1424 * mkstemp() templates, i.e. contain the string "XXXXXX".
1425 * g_mkstemp_full() is slightly more flexible than mkstemp()
1426 * in that the sequence does not have to occur at the very end of the
1427 * template and you can pass a @mode and additional @flags. The X
1428 * string will be modified to form the name of a file that didn't exist.
1429 * The string should be in the GLib file name encoding. Most importantly,
1430 * on Windows it should be in UTF-8.
1432 * Returns: A file handle (as from open()) to the file
1433 * opened for reading and writing. The file handle should be
1434 * closed with close(). In case of errors, -1 is returned
1435 * and %errno will be set.
1437 * Since: 2.22
1439 gint
1440 g_mkstemp_full (gchar *tmpl,
1441 gint flags,
1442 gint mode)
1444 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1445 return get_tmp_file (tmpl, wrap_g_open,
1446 flags | O_CREAT | O_EXCL, mode);
1450 * g_mkstemp:
1451 * @tmpl: (type filename): template filename
1453 * Opens a temporary file. See the mkstemp() documentation
1454 * on most UNIX-like systems.
1456 * The parameter is a string that should follow the rules for
1457 * mkstemp() templates, i.e. contain the string "XXXXXX".
1458 * g_mkstemp() is slightly more flexible than mkstemp() in that the
1459 * sequence does not have to occur at the very end of the template.
1460 * The X string will be modified to form the name of a file that
1461 * didn't exist. The string should be in the GLib file name encoding.
1462 * Most importantly, on Windows it should be in UTF-8.
1464 * Returns: A file handle (as from open()) to the file
1465 * opened for reading and writing. The file is opened in binary
1466 * mode on platforms where there is a difference. The file handle
1467 * should be closed with close(). In case of errors, -1 is
1468 * returned and %errno will be set.
1470 gint
1471 g_mkstemp (gchar *tmpl)
1473 return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1476 static gint
1477 g_get_tmp_name (const gchar *tmpl,
1478 gchar **name_used,
1479 GTmpFileCallback f,
1480 gint flags,
1481 gint mode,
1482 GError **error)
1484 int retval;
1485 const char *tmpdir;
1486 const char *sep;
1487 char *fulltemplate;
1488 const char *slash;
1490 if (tmpl == NULL)
1491 tmpl = ".XXXXXX";
1493 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1494 #ifdef G_OS_WIN32
1495 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1496 #endif
1499 gchar *display_tmpl = g_filename_display_name (tmpl);
1500 char c[2];
1501 c[0] = *slash;
1502 c[1] = '\0';
1504 g_set_error (error,
1505 G_FILE_ERROR,
1506 G_FILE_ERROR_FAILED,
1507 _("Template '%s' invalid, should not contain a '%s'"),
1508 display_tmpl, c);
1509 g_free (display_tmpl);
1511 return -1;
1514 if (strstr (tmpl, "XXXXXX") == NULL)
1516 gchar *display_tmpl = g_filename_display_name (tmpl);
1517 g_set_error (error,
1518 G_FILE_ERROR,
1519 G_FILE_ERROR_FAILED,
1520 _("Template '%s' doesn't contain XXXXXX"),
1521 display_tmpl);
1522 g_free (display_tmpl);
1523 return -1;
1526 tmpdir = g_get_tmp_dir ();
1528 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1529 sep = "";
1530 else
1531 sep = G_DIR_SEPARATOR_S;
1533 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1535 retval = get_tmp_file (fulltemplate, f, flags, mode);
1536 if (retval == -1)
1538 int saved_errno = errno;
1539 set_file_error (error,
1540 fulltemplate,
1541 _("Failed to create file '%s': %s"),
1542 saved_errno);
1543 g_free (fulltemplate);
1544 return -1;
1547 *name_used = fulltemplate;
1549 return retval;
1553 * g_file_open_tmp:
1554 * @tmpl: (type filename) (allow-none): Template for file name, as in
1555 * g_mkstemp(), basename only, or %NULL for a default template
1556 * @name_used: (out) (type filename): location to store actual name used,
1557 * or %NULL
1558 * @error: return location for a #GError
1560 * Opens a file for writing in the preferred directory for temporary
1561 * files (as returned by g_get_tmp_dir()).
1563 * @tmpl should be a string in the GLib file name encoding containing
1564 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1565 * However, unlike these functions, the template should only be a
1566 * basename, no directory components are allowed. If template is
1567 * %NULL, a default template is used.
1569 * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
1570 * modified, and might thus be a read-only literal string.
1572 * Upon success, and if @name_used is non-%NULL, the actual name used
1573 * is returned in @name_used. This string should be freed with g_free()
1574 * when not needed any longer. The returned name is in the GLib file
1575 * name encoding.
1577 * Returns: A file handle (as from open()) to the file opened for
1578 * reading and writing. The file is opened in binary mode on platforms
1579 * where there is a difference. The file handle should be closed with
1580 * close(). In case of errors, -1 is returned and @error will be set.
1582 gint
1583 g_file_open_tmp (const gchar *tmpl,
1584 gchar **name_used,
1585 GError **error)
1587 gchar *fulltemplate;
1588 gint result;
1590 result = g_get_tmp_name (tmpl, &fulltemplate,
1591 wrap_g_open,
1592 O_CREAT | O_EXCL | O_RDWR | O_BINARY,
1593 0600,
1594 error);
1595 if (result != -1)
1597 if (name_used)
1598 *name_used = fulltemplate;
1599 else
1600 g_free (fulltemplate);
1603 return result;
1607 * g_dir_make_tmp:
1608 * @tmpl: (type filename) (allow-none): Template for directory name,
1609 * as in g_mkdtemp(), basename only, or %NULL for a default template
1610 * @error: return location for a #GError
1612 * Creates a subdirectory in the preferred directory for temporary
1613 * files (as returned by g_get_tmp_dir()).
1615 * @tmpl should be a string in the GLib file name encoding containing
1616 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1617 * However, unlike these functions, the template should only be a
1618 * basename, no directory components are allowed. If template is
1619 * %NULL, a default template is used.
1621 * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
1622 * modified, and might thus be a read-only literal string.
1624 * Returns: (type filename): The actual name used. This string
1625 * should be freed with g_free() when not needed any longer and is
1626 * is in the GLib file name encoding. In case of errors, %NULL is
1627 * returned and @error will be set.
1629 * Since: 2.30
1631 gchar *
1632 g_dir_make_tmp (const gchar *tmpl,
1633 GError **error)
1635 gchar *fulltemplate;
1637 if (g_get_tmp_name (tmpl, &fulltemplate, wrap_g_mkdir, 0, 0700, error) == -1)
1638 return NULL;
1639 else
1640 return fulltemplate;
1643 static gchar *
1644 g_build_path_va (const gchar *separator,
1645 const gchar *first_element,
1646 va_list *args,
1647 gchar **str_array)
1649 GString *result;
1650 gint separator_len = strlen (separator);
1651 gboolean is_first = TRUE;
1652 gboolean have_leading = FALSE;
1653 const gchar *single_element = NULL;
1654 const gchar *next_element;
1655 const gchar *last_trailing = NULL;
1656 gint i = 0;
1658 result = g_string_new (NULL);
1660 if (str_array)
1661 next_element = str_array[i++];
1662 else
1663 next_element = first_element;
1665 while (TRUE)
1667 const gchar *element;
1668 const gchar *start;
1669 const gchar *end;
1671 if (next_element)
1673 element = next_element;
1674 if (str_array)
1675 next_element = str_array[i++];
1676 else
1677 next_element = va_arg (*args, gchar *);
1679 else
1680 break;
1682 /* Ignore empty elements */
1683 if (!*element)
1684 continue;
1686 start = element;
1688 if (separator_len)
1690 while (strncmp (start, separator, separator_len) == 0)
1691 start += separator_len;
1694 end = start + strlen (start);
1696 if (separator_len)
1698 while (end >= start + separator_len &&
1699 strncmp (end - separator_len, separator, separator_len) == 0)
1700 end -= separator_len;
1702 last_trailing = end;
1703 while (last_trailing >= element + separator_len &&
1704 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1705 last_trailing -= separator_len;
1707 if (!have_leading)
1709 /* If the leading and trailing separator strings are in the
1710 * same element and overlap, the result is exactly that element
1712 if (last_trailing <= start)
1713 single_element = element;
1715 g_string_append_len (result, element, start - element);
1716 have_leading = TRUE;
1718 else
1719 single_element = NULL;
1722 if (end == start)
1723 continue;
1725 if (!is_first)
1726 g_string_append (result, separator);
1728 g_string_append_len (result, start, end - start);
1729 is_first = FALSE;
1732 if (single_element)
1734 g_string_free (result, TRUE);
1735 return g_strdup (single_element);
1737 else
1739 if (last_trailing)
1740 g_string_append (result, last_trailing);
1742 return g_string_free (result, FALSE);
1747 * g_build_pathv:
1748 * @separator: a string used to separator the elements of the path.
1749 * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
1750 * array of strings containing the path elements.
1752 * Behaves exactly like g_build_path(), but takes the path elements
1753 * as a string array, instead of varargs. This function is mainly
1754 * meant for language bindings.
1756 * Returns: (type filename): a newly-allocated string that must be freed
1757 * with g_free().
1759 * Since: 2.8
1761 gchar *
1762 g_build_pathv (const gchar *separator,
1763 gchar **args)
1765 if (!args)
1766 return NULL;
1768 return g_build_path_va (separator, NULL, NULL, args);
1773 * g_build_path:
1774 * @separator: a string used to separator the elements of the path.
1775 * @first_element: the first element in the path
1776 * @...: remaining elements in path, terminated by %NULL
1778 * Creates a path from a series of elements using @separator as the
1779 * separator between elements. At the boundary between two elements,
1780 * any trailing occurrences of separator in the first element, or
1781 * leading occurrences of separator in the second element are removed
1782 * and exactly one copy of the separator is inserted.
1784 * Empty elements are ignored.
1786 * The number of leading copies of the separator on the result is
1787 * the same as the number of leading copies of the separator on
1788 * the first non-empty element.
1790 * The number of trailing copies of the separator on the result is
1791 * the same as the number of trailing copies of the separator on
1792 * the last non-empty element. (Determination of the number of
1793 * trailing copies is done without stripping leading copies, so
1794 * if the separator is `ABA`, then `ABABA` has 1 trailing copy.)
1796 * However, if there is only a single non-empty element, and there
1797 * are no characters in that element not part of the leading or
1798 * trailing separators, then the result is exactly the original value
1799 * of that element.
1801 * Other than for determination of the number of leading and trailing
1802 * copies of the separator, elements consisting only of copies
1803 * of the separator are ignored.
1805 * Returns: a newly-allocated string that must be freed with g_free().
1807 gchar *
1808 g_build_path (const gchar *separator,
1809 const gchar *first_element,
1810 ...)
1812 gchar *str;
1813 va_list args;
1815 g_return_val_if_fail (separator != NULL, NULL);
1817 va_start (args, first_element);
1818 str = g_build_path_va (separator, first_element, &args, NULL);
1819 va_end (args);
1821 return str;
1824 #ifdef G_OS_WIN32
1826 static gchar *
1827 g_build_pathname_va (const gchar *first_element,
1828 va_list *args,
1829 gchar **str_array)
1831 /* Code copied from g_build_pathv(), and modified to use two
1832 * alternative single-character separators.
1834 GString *result;
1835 gboolean is_first = TRUE;
1836 gboolean have_leading = FALSE;
1837 const gchar *single_element = NULL;
1838 const gchar *next_element;
1839 const gchar *last_trailing = NULL;
1840 gchar current_separator = '\\';
1841 gint i = 0;
1843 result = g_string_new (NULL);
1845 if (str_array)
1846 next_element = str_array[i++];
1847 else
1848 next_element = first_element;
1850 while (TRUE)
1852 const gchar *element;
1853 const gchar *start;
1854 const gchar *end;
1856 if (next_element)
1858 element = next_element;
1859 if (str_array)
1860 next_element = str_array[i++];
1861 else
1862 next_element = va_arg (*args, gchar *);
1864 else
1865 break;
1867 /* Ignore empty elements */
1868 if (!*element)
1869 continue;
1871 start = element;
1873 if (TRUE)
1875 while (start &&
1876 (*start == '\\' || *start == '/'))
1878 current_separator = *start;
1879 start++;
1883 end = start + strlen (start);
1885 if (TRUE)
1887 while (end >= start + 1 &&
1888 (end[-1] == '\\' || end[-1] == '/'))
1890 current_separator = end[-1];
1891 end--;
1894 last_trailing = end;
1895 while (last_trailing >= element + 1 &&
1896 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1897 last_trailing--;
1899 if (!have_leading)
1901 /* If the leading and trailing separator strings are in the
1902 * same element and overlap, the result is exactly that element
1904 if (last_trailing <= start)
1905 single_element = element;
1907 g_string_append_len (result, element, start - element);
1908 have_leading = TRUE;
1910 else
1911 single_element = NULL;
1914 if (end == start)
1915 continue;
1917 if (!is_first)
1918 g_string_append_len (result, &current_separator, 1);
1920 g_string_append_len (result, start, end - start);
1921 is_first = FALSE;
1924 if (single_element)
1926 g_string_free (result, TRUE);
1927 return g_strdup (single_element);
1929 else
1931 if (last_trailing)
1932 g_string_append (result, last_trailing);
1934 return g_string_free (result, FALSE);
1938 #endif
1941 * g_build_filenamev:
1942 * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
1943 * array of strings containing the path elements.
1945 * Behaves exactly like g_build_filename(), but takes the path elements
1946 * as a string array, instead of varargs. This function is mainly
1947 * meant for language bindings.
1949 * Returns: (type filename): a newly-allocated string that must be freed
1950 * with g_free().
1952 * Since: 2.8
1954 gchar *
1955 g_build_filenamev (gchar **args)
1957 gchar *str;
1959 #ifndef G_OS_WIN32
1960 str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1961 #else
1962 str = g_build_pathname_va (NULL, NULL, args);
1963 #endif
1965 return str;
1969 * g_build_filename:
1970 * @first_element: the first element in the path
1971 * @...: remaining elements in path, terminated by %NULL
1973 * Creates a filename from a series of elements using the correct
1974 * separator for filenames.
1976 * On Unix, this function behaves identically to `g_build_path
1977 * (G_DIR_SEPARATOR_S, first_element, ....)`.
1979 * On Windows, it takes into account that either the backslash
1980 * (`\` or slash (`/`) can be used as separator in filenames, but
1981 * otherwise behaves as on UNIX. When file pathname separators need
1982 * to be inserted, the one that last previously occurred in the
1983 * parameters (reading from left to right) is used.
1985 * No attempt is made to force the resulting filename to be an absolute
1986 * path. If the first element is a relative path, the result will
1987 * be a relative path.
1989 * Returns: a newly-allocated string that must be freed with g_free().
1991 gchar *
1992 g_build_filename (const gchar *first_element,
1993 ...)
1995 gchar *str;
1996 va_list args;
1998 va_start (args, first_element);
1999 #ifndef G_OS_WIN32
2000 str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
2001 #else
2002 str = g_build_pathname_va (first_element, &args, NULL);
2003 #endif
2004 va_end (args);
2006 return str;
2010 * g_file_read_link:
2011 * @filename: (type filename): the symbolic link
2012 * @error: return location for a #GError
2014 * Reads the contents of the symbolic link @filename like the POSIX
2015 * readlink() function. The returned string is in the encoding used
2016 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
2018 * Returns: (type filename): A newly-allocated string with the contents of
2019 * the symbolic link, or %NULL if an error occurred.
2021 * Since: 2.4
2023 gchar *
2024 g_file_read_link (const gchar *filename,
2025 GError **error)
2027 #ifdef HAVE_READLINK
2028 gchar *buffer;
2029 guint size;
2030 gint read_size;
2032 size = 256;
2033 buffer = g_malloc (size);
2035 while (TRUE)
2037 read_size = readlink (filename, buffer, size);
2038 if (read_size < 0)
2040 int saved_errno = errno;
2041 set_file_error (error,
2042 filename,
2043 _("Failed to read the symbolic link '%s': %s"),
2044 saved_errno);
2045 g_free (buffer);
2046 return NULL;
2049 if (read_size < size)
2051 buffer[read_size] = 0;
2052 return buffer;
2055 size *= 2;
2056 buffer = g_realloc (buffer, size);
2058 #else
2059 g_set_error_literal (error,
2060 G_FILE_ERROR,
2061 G_FILE_ERROR_INVAL,
2062 _("Symbolic links not supported"));
2064 return NULL;
2065 #endif
2069 * g_path_is_absolute:
2070 * @file_name: (type filename): a file name
2072 * Returns %TRUE if the given @file_name is an absolute file name.
2073 * Note that this is a somewhat vague concept on Windows.
2075 * On POSIX systems, an absolute file name is well-defined. It always
2076 * starts from the single root directory. For example "/usr/local".
2078 * On Windows, the concepts of current drive and drive-specific
2079 * current directory introduce vagueness. This function interprets as
2080 * an absolute file name one that either begins with a directory
2081 * separator such as "\Users\tml" or begins with the root on a drive,
2082 * for example "C:\Windows". The first case also includes UNC paths
2083 * such as "\\myserver\docs\foo". In all cases, either slashes or
2084 * backslashes are accepted.
2086 * Note that a file name relative to the current drive root does not
2087 * truly specify a file uniquely over time and across processes, as
2088 * the current drive is a per-process value and can be changed.
2090 * File names relative the current directory on some specific drive,
2091 * such as "D:foo/bar", are not interpreted as absolute by this
2092 * function, but they obviously are not relative to the normal current
2093 * directory as returned by getcwd() or g_get_current_dir()
2094 * either. Such paths should be avoided, or need to be handled using
2095 * Windows-specific code.
2097 * Returns: %TRUE if @file_name is absolute
2099 gboolean
2100 g_path_is_absolute (const gchar *file_name)
2102 g_return_val_if_fail (file_name != NULL, FALSE);
2104 if (G_IS_DIR_SEPARATOR (file_name[0]))
2105 return TRUE;
2107 #ifdef G_OS_WIN32
2108 /* Recognize drive letter on native Windows */
2109 if (g_ascii_isalpha (file_name[0]) &&
2110 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
2111 return TRUE;
2112 #endif
2114 return FALSE;
2118 * g_path_skip_root:
2119 * @file_name: (type filename): a file name
2121 * Returns a pointer into @file_name after the root component,
2122 * i.e. after the "/" in UNIX or "C:\" under Windows. If @file_name
2123 * is not an absolute path it returns %NULL.
2125 * Returns: (type filename) (nullable): a pointer into @file_name after the
2126 * root component
2128 const gchar *
2129 g_path_skip_root (const gchar *file_name)
2131 g_return_val_if_fail (file_name != NULL, NULL);
2133 #ifdef G_PLATFORM_WIN32
2134 /* Skip \\server\share or //server/share */
2135 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2136 G_IS_DIR_SEPARATOR (file_name[1]) &&
2137 file_name[2] &&
2138 !G_IS_DIR_SEPARATOR (file_name[2]))
2140 gchar *p;
2141 p = strchr (file_name + 2, G_DIR_SEPARATOR);
2143 #ifdef G_OS_WIN32
2145 gchar *q;
2147 q = strchr (file_name + 2, '/');
2148 if (p == NULL || (q != NULL && q < p))
2149 p = q;
2151 #endif
2153 if (p && p > file_name + 2 && p[1])
2155 file_name = p + 1;
2157 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
2158 file_name++;
2160 /* Possibly skip a backslash after the share name */
2161 if (G_IS_DIR_SEPARATOR (file_name[0]))
2162 file_name++;
2164 return (gchar *)file_name;
2167 #endif
2169 /* Skip initial slashes */
2170 if (G_IS_DIR_SEPARATOR (file_name[0]))
2172 while (G_IS_DIR_SEPARATOR (file_name[0]))
2173 file_name++;
2174 return (gchar *)file_name;
2177 #ifdef G_OS_WIN32
2178 /* Skip X:\ */
2179 if (g_ascii_isalpha (file_name[0]) &&
2180 file_name[1] == ':' &&
2181 G_IS_DIR_SEPARATOR (file_name[2]))
2182 return (gchar *)file_name + 3;
2183 #endif
2185 return NULL;
2189 * g_basename:
2190 * @file_name: (type filename): the name of the file
2192 * Gets the name of the file without any leading directory
2193 * components. It returns a pointer into the given file name
2194 * string.
2196 * Returns: (type filename): the name of the file without any leading
2197 * directory components
2199 * Deprecated:2.2: Use g_path_get_basename() instead, but notice
2200 * that g_path_get_basename() allocates new memory for the
2201 * returned string, unlike this function which returns a pointer
2202 * into the argument.
2204 const gchar *
2205 g_basename (const gchar *file_name)
2207 gchar *base;
2209 g_return_val_if_fail (file_name != NULL, NULL);
2211 base = strrchr (file_name, G_DIR_SEPARATOR);
2213 #ifdef G_OS_WIN32
2215 gchar *q;
2216 q = strrchr (file_name, '/');
2217 if (base == NULL || (q != NULL && q > base))
2218 base = q;
2220 #endif
2222 if (base)
2223 return base + 1;
2225 #ifdef G_OS_WIN32
2226 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2227 return (gchar*) file_name + 2;
2228 #endif
2230 return (gchar*) file_name;
2234 * g_path_get_basename:
2235 * @file_name: (type filename): the name of the file
2237 * Gets the last component of the filename.
2239 * If @file_name ends with a directory separator it gets the component
2240 * before the last slash. If @file_name consists only of directory
2241 * separators (and on Windows, possibly a drive letter), a single
2242 * separator is returned. If @file_name is empty, it gets ".".
2244 * Returns: (type filename): a newly allocated string containing the last
2245 * component of the filename
2247 gchar *
2248 g_path_get_basename (const gchar *file_name)
2250 gssize base;
2251 gssize last_nonslash;
2252 gsize len;
2253 gchar *retval;
2255 g_return_val_if_fail (file_name != NULL, NULL);
2257 if (file_name[0] == '\0')
2258 return g_strdup (".");
2260 last_nonslash = strlen (file_name) - 1;
2262 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
2263 last_nonslash--;
2265 if (last_nonslash == -1)
2266 /* string only containing slashes */
2267 return g_strdup (G_DIR_SEPARATOR_S);
2269 #ifdef G_OS_WIN32
2270 if (last_nonslash == 1 &&
2271 g_ascii_isalpha (file_name[0]) &&
2272 file_name[1] == ':')
2273 /* string only containing slashes and a drive */
2274 return g_strdup (G_DIR_SEPARATOR_S);
2275 #endif
2276 base = last_nonslash;
2278 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
2279 base--;
2281 #ifdef G_OS_WIN32
2282 if (base == -1 &&
2283 g_ascii_isalpha (file_name[0]) &&
2284 file_name[1] == ':')
2285 base = 1;
2286 #endif /* G_OS_WIN32 */
2288 len = last_nonslash - base;
2289 retval = g_malloc (len + 1);
2290 memcpy (retval, file_name + base + 1, len);
2291 retval [len] = '\0';
2293 return retval;
2297 * g_dirname:
2298 * @file_name: the name of the file
2300 * Gets the directory components of a file name.
2302 * If the file name has no directory components "." is returned.
2303 * The returned string should be freed when no longer needed.
2305 * Returns: the directory components of the file
2307 * Deprecated: use g_path_get_dirname() instead
2311 * g_path_get_dirname:
2312 * @file_name: (type filename): the name of the file
2314 * Gets the directory components of a file name.
2316 * If the file name has no directory components "." is returned.
2317 * The returned string should be freed when no longer needed.
2319 * Returns: (type filename): the directory components of the file
2321 gchar *
2322 g_path_get_dirname (const gchar *file_name)
2324 gchar *base;
2325 gsize len;
2327 g_return_val_if_fail (file_name != NULL, NULL);
2329 base = strrchr (file_name, G_DIR_SEPARATOR);
2331 #ifdef G_OS_WIN32
2333 gchar *q;
2334 q = strrchr (file_name, '/');
2335 if (base == NULL || (q != NULL && q > base))
2336 base = q;
2338 #endif
2340 if (!base)
2342 #ifdef G_OS_WIN32
2343 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2345 gchar drive_colon_dot[4];
2347 drive_colon_dot[0] = file_name[0];
2348 drive_colon_dot[1] = ':';
2349 drive_colon_dot[2] = '.';
2350 drive_colon_dot[3] = '\0';
2352 return g_strdup (drive_colon_dot);
2354 #endif
2355 return g_strdup (".");
2358 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
2359 base--;
2361 #ifdef G_OS_WIN32
2362 /* base points to the char before the last slash.
2364 * In case file_name is the root of a drive (X:\) or a child of the
2365 * root of a drive (X:\foo), include the slash.
2367 * In case file_name is the root share of an UNC path
2368 * (\\server\share), add a slash, returning \\server\share\ .
2370 * In case file_name is a direct child of a share in an UNC path
2371 * (\\server\share\foo), include the slash after the share name,
2372 * returning \\server\share\ .
2374 if (base == file_name + 1 &&
2375 g_ascii_isalpha (file_name[0]) &&
2376 file_name[1] == ':')
2377 base++;
2378 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2379 G_IS_DIR_SEPARATOR (file_name[1]) &&
2380 file_name[2] &&
2381 !G_IS_DIR_SEPARATOR (file_name[2]) &&
2382 base >= file_name + 2)
2384 const gchar *p = file_name + 2;
2385 while (*p && !G_IS_DIR_SEPARATOR (*p))
2386 p++;
2387 if (p == base + 1)
2389 len = (guint) strlen (file_name) + 1;
2390 base = g_new (gchar, len + 1);
2391 strcpy (base, file_name);
2392 base[len-1] = G_DIR_SEPARATOR;
2393 base[len] = 0;
2394 return base;
2396 if (G_IS_DIR_SEPARATOR (*p))
2398 p++;
2399 while (*p && !G_IS_DIR_SEPARATOR (*p))
2400 p++;
2401 if (p == base + 1)
2402 base++;
2405 #endif
2407 len = (guint) 1 + base - file_name;
2408 base = g_new (gchar, len + 1);
2409 memmove (base, file_name, len);
2410 base[len] = 0;
2412 return base;
2415 #if defined(MAXPATHLEN)
2416 #define G_PATH_LENGTH MAXPATHLEN
2417 #elif defined(PATH_MAX)
2418 #define G_PATH_LENGTH PATH_MAX
2419 #elif defined(_PC_PATH_MAX)
2420 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
2421 #else
2422 #define G_PATH_LENGTH 2048
2423 #endif
2426 * g_get_current_dir:
2428 * Gets the current directory.
2430 * The returned string should be freed when no longer needed.
2431 * The encoding of the returned string is system defined.
2432 * On Windows, it is always UTF-8.
2434 * Since GLib 2.40, this function will return the value of the "PWD"
2435 * environment variable if it is set and it happens to be the same as
2436 * the current directory. This can make a difference in the case that
2437 * the current directory is the target of a symbolic link.
2439 * Returns: (type filename): the current directory
2441 gchar *
2442 g_get_current_dir (void)
2444 #ifdef G_OS_WIN32
2446 gchar *dir = NULL;
2447 wchar_t dummy[2], *wdir;
2448 int len;
2450 len = GetCurrentDirectoryW (2, dummy);
2451 wdir = g_new (wchar_t, len);
2453 if (GetCurrentDirectoryW (len, wdir) == len - 1)
2454 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
2456 g_free (wdir);
2458 if (dir == NULL)
2459 dir = g_strdup ("\\");
2461 return dir;
2463 #else
2464 const gchar *pwd;
2465 gchar *buffer = NULL;
2466 gchar *dir = NULL;
2467 static gulong max_len = 0;
2468 struct stat pwdbuf, dotbuf;
2470 pwd = g_getenv ("PWD");
2471 if (pwd != NULL &&
2472 g_stat (".", &dotbuf) == 0 && g_stat (pwd, &pwdbuf) == 0 &&
2473 dotbuf.st_dev == pwdbuf.st_dev && dotbuf.st_ino == pwdbuf.st_ino)
2474 return g_strdup (pwd);
2476 if (max_len == 0)
2477 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
2479 while (max_len < G_MAXULONG / 2)
2481 g_free (buffer);
2482 buffer = g_new (gchar, max_len + 1);
2483 *buffer = 0;
2484 dir = getcwd (buffer, max_len);
2486 if (dir || errno != ERANGE)
2487 break;
2489 max_len *= 2;
2492 if (!dir || !*buffer)
2494 /* hm, should we g_error() out here?
2495 * this can happen if e.g. "./" has mode \0000
2497 buffer[0] = G_DIR_SEPARATOR;
2498 buffer[1] = 0;
2501 dir = g_strdup (buffer);
2502 g_free (buffer);
2504 return dir;
2506 #endif /* !G_OS_WIN32 */
2510 /* NOTE : Keep this part last to ensure nothing in this file uses thn
2511 * below binary compatibility versions.
2513 #if defined (G_OS_WIN32) && !defined (_WIN64)
2515 /* Binary compatibility versions. Will be called by code compiled
2516 * against quite old (pre-2.8, I think) headers only, not from more
2517 * recently compiled code.
2520 #undef g_file_test
2522 gboolean
2523 g_file_test (const gchar *filename,
2524 GFileTest test)
2526 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
2527 gboolean retval;
2529 if (utf8_filename == NULL)
2530 return FALSE;
2532 retval = g_file_test_utf8 (utf8_filename, test);
2534 g_free (utf8_filename);
2536 return retval;
2539 #undef g_file_get_contents
2541 gboolean
2542 g_file_get_contents (const gchar *filename,
2543 gchar **contents,
2544 gsize *length,
2545 GError **error)
2547 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
2548 gboolean retval;
2550 if (utf8_filename == NULL)
2551 return FALSE;
2553 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
2555 g_free (utf8_filename);
2557 return retval;
2560 #undef g_mkstemp
2562 static gint
2563 wrap_libc_open (const gchar *filename,
2564 int flags,
2565 int mode)
2567 return open (filename, flags, mode);
2570 gint
2571 g_mkstemp (gchar *tmpl)
2573 /* This is the backward compatibility system codepage version,
2574 * thus use normal open().
2576 return get_tmp_file (tmpl, wrap_libc_open,
2577 O_RDWR | O_CREAT | O_EXCL, 0600);
2580 #undef g_file_open_tmp
2582 gint
2583 g_file_open_tmp (const gchar *tmpl,
2584 gchar **name_used,
2585 GError **error)
2587 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
2588 gchar *utf8_name_used;
2589 gint retval;
2591 if (utf8_tmpl == NULL)
2592 return -1;
2594 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
2596 if (retval == -1)
2597 return -1;
2599 if (name_used)
2600 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
2602 g_free (utf8_name_used);
2604 return retval;
2607 #undef g_get_current_dir
2609 gchar *
2610 g_get_current_dir (void)
2612 gchar *utf8_dir = g_get_current_dir_utf8 ();
2613 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
2614 g_free (utf8_dir);
2615 return dir;
2618 #endif