Add some more cases to the app-id unit tests
[glib.git] / glib / gfileutils.c
blobdaac6edff1857ebafd10f0d50ab523956b4c1451
1 /* gfileutils.c - File utility functions
3 * Copyright 2000 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library 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 License
16 * along with this library; if not, see <http://www.gnu.org/licenses/>.
19 #include "config.h"
20 #include "glibconfig.h"
22 #include <sys/stat.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <fcntl.h>
31 #include <stdlib.h>
33 #ifdef G_OS_UNIX
34 #include <unistd.h>
35 #endif
36 #ifdef G_OS_WIN32
37 #include <windows.h>
38 #include <io.h>
39 #endif /* G_OS_WIN32 */
41 #ifndef S_ISLNK
42 #define S_ISLNK(x) 0
43 #endif
45 #ifndef O_BINARY
46 #define O_BINARY 0
47 #endif
49 #include "gfileutils.h"
51 #include "gstdio.h"
52 #include "glibintl.h"
54 #ifdef HAVE_LINUX_MAGIC_H /* for btrfs check */
55 #include <linux/magic.h>
56 #include <sys/vfs.h>
57 #endif
60 /**
61 * SECTION:fileutils
62 * @title: File Utilities
63 * @short_description: various file-related functions
65 * There is a group of functions which wrap the common POSIX functions
66 * dealing with filenames (g_open(), g_rename(), g_mkdir(), g_stat(),
67 * g_unlink(), g_remove(), g_fopen(), g_freopen()). The point of these
68 * wrappers is to make it possible to handle file names with any Unicode
69 * characters in them on Windows without having to use ifdefs and the
70 * wide character API in the application code.
72 * The pathname argument should be in the GLib file name encoding.
73 * On POSIX this is the actual on-disk encoding which might correspond
74 * to the locale settings of the process (or the `G_FILENAME_ENCODING`
75 * environment variable), or not.
77 * On Windows the GLib file name encoding is UTF-8. Note that the
78 * Microsoft C library does not use UTF-8, but has separate APIs for
79 * current system code page and wide characters (UTF-16). The GLib
80 * wrappers call the wide character API if present (on modern Windows
81 * systems), otherwise convert to/from the system code page.
83 * Another group of functions allows to open and read directories
84 * in the GLib file name encoding. These are g_dir_open(),
85 * g_dir_read_name(), g_dir_rewind(), g_dir_close().
88 /**
89 * GFileError:
90 * @G_FILE_ERROR_EXIST: Operation not permitted; only the owner of
91 * the file (or other resource) or processes with special privileges
92 * can perform the operation.
93 * @G_FILE_ERROR_ISDIR: File is a directory; you cannot open a directory
94 * for writing, or create or remove hard links to it.
95 * @G_FILE_ERROR_ACCES: Permission denied; the file permissions do not
96 * allow the attempted operation.
97 * @G_FILE_ERROR_NAMETOOLONG: Filename too long.
98 * @G_FILE_ERROR_NOENT: No such file or directory. This is a "file
99 * doesn't exist" error for ordinary files that are referenced in
100 * contexts where they are expected to already exist.
101 * @G_FILE_ERROR_NOTDIR: A file that isn't a directory was specified when
102 * a directory is required.
103 * @G_FILE_ERROR_NXIO: No such device or address. The system tried to
104 * use the device represented by a file you specified, and it
105 * couldn't find the device. This can mean that the device file was
106 * installed incorrectly, or that the physical device is missing or
107 * not correctly attached to the computer.
108 * @G_FILE_ERROR_NODEV: The underlying file system of the specified file
109 * does not support memory mapping.
110 * @G_FILE_ERROR_ROFS: The directory containing the new link can't be
111 * modified because it's on a read-only file system.
112 * @G_FILE_ERROR_TXTBSY: Text file busy.
113 * @G_FILE_ERROR_FAULT: You passed in a pointer to bad memory.
114 * (GLib won't reliably return this, don't pass in pointers to bad
115 * memory.)
116 * @G_FILE_ERROR_LOOP: Too many levels of symbolic links were encountered
117 * in looking up a file name. This often indicates a cycle of symbolic
118 * links.
119 * @G_FILE_ERROR_NOSPC: No space left on device; write operation on a
120 * file failed because the disk is full.
121 * @G_FILE_ERROR_NOMEM: No memory available. The system cannot allocate
122 * more virtual memory because its capacity is full.
123 * @G_FILE_ERROR_MFILE: The current process has too many files open and
124 * can't open any more. Duplicate descriptors do count toward this
125 * limit.
126 * @G_FILE_ERROR_NFILE: There are too many distinct file openings in the
127 * entire system.
128 * @G_FILE_ERROR_BADF: Bad file descriptor; for example, I/O on a
129 * descriptor that has been closed or reading from a descriptor open
130 * only for writing (or vice versa).
131 * @G_FILE_ERROR_INVAL: Invalid argument. This is used to indicate
132 * various kinds of problems with passing the wrong argument to a
133 * library function.
134 * @G_FILE_ERROR_PIPE: Broken pipe; there is no process reading from the
135 * other end of a pipe. Every library function that returns this
136 * error code also generates a 'SIGPIPE' signal; this signal
137 * terminates the program if not handled or blocked. Thus, your
138 * program will never actually see this code unless it has handled
139 * or blocked 'SIGPIPE'.
140 * @G_FILE_ERROR_AGAIN: Resource temporarily unavailable; the call might
141 * work if you try again later.
142 * @G_FILE_ERROR_INTR: Interrupted function call; an asynchronous signal
143 * occurred and prevented completion of the call. When this
144 * happens, you should try the call again.
145 * @G_FILE_ERROR_IO: Input/output error; usually used for physical read
146 * or write errors. i.e. the disk or other physical device hardware
147 * is returning errors.
148 * @G_FILE_ERROR_PERM: Operation not permitted; only the owner of the
149 * file (or other resource) or processes with special privileges can
150 * perform the operation.
151 * @G_FILE_ERROR_NOSYS: Function not implemented; this indicates that
152 * the system is missing some functionality.
153 * @G_FILE_ERROR_FAILED: Does not correspond to a UNIX error code; this
154 * is the standard "failed for unspecified reason" error code present
155 * in all #GError error code enumerations. Returned if no specific
156 * code applies.
158 * Values corresponding to @errno codes returned from file operations
159 * on UNIX. Unlike @errno codes, GFileError values are available on
160 * all systems, even Windows. The exact meaning of each code depends
161 * on what sort of file operation you were performing; the UNIX
162 * documentation gives more details. The following error code descriptions
163 * come from the GNU C Library manual, and are under the copyright
164 * of that manual.
166 * It's not very portable to make detailed assumptions about exactly
167 * which errors will be returned from a given operation. Some errors
168 * don't occur on some systems, etc., sometimes there are subtle
169 * differences in when a system will report a given error, etc.
173 * G_FILE_ERROR:
175 * Error domain for file operations. Errors in this domain will
176 * be from the #GFileError enumeration. See #GError for information
177 * on error domains.
181 * GFileTest:
182 * @G_FILE_TEST_IS_REGULAR: %TRUE if the file is a regular file
183 * (not a directory). Note that this test will also return %TRUE
184 * if the tested file is a symlink to a regular file.
185 * @G_FILE_TEST_IS_SYMLINK: %TRUE if the file is a symlink.
186 * @G_FILE_TEST_IS_DIR: %TRUE if the file is a directory.
187 * @G_FILE_TEST_IS_EXECUTABLE: %TRUE if the file is executable.
188 * @G_FILE_TEST_EXISTS: %TRUE if the file exists. It may or may not
189 * be a regular file.
191 * A test to perform on a file using g_file_test().
195 * g_mkdir_with_parents:
196 * @pathname: (type filename): a pathname in the GLib file name encoding
197 * @mode: permissions to use for newly created directories
199 * Create a directory if it doesn't already exist. Create intermediate
200 * parent directories as needed, too.
202 * Returns: 0 if the directory already exists, or was successfully
203 * created. Returns -1 if an error occurred, with errno set.
205 * Since: 2.8
208 g_mkdir_with_parents (const gchar *pathname,
209 int mode)
211 gchar *fn, *p;
213 if (pathname == NULL || *pathname == '\0')
215 errno = EINVAL;
216 return -1;
219 fn = g_strdup (pathname);
221 if (g_path_is_absolute (fn))
222 p = (gchar *) g_path_skip_root (fn);
223 else
224 p = fn;
228 while (*p && !G_IS_DIR_SEPARATOR (*p))
229 p++;
231 if (!*p)
232 p = NULL;
233 else
234 *p = '\0';
236 if (!g_file_test (fn, G_FILE_TEST_EXISTS))
238 if (g_mkdir (fn, mode) == -1 && errno != EEXIST)
240 int errno_save = errno;
241 g_free (fn);
242 errno = errno_save;
243 return -1;
246 else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
248 g_free (fn);
249 errno = ENOTDIR;
250 return -1;
252 if (p)
254 *p++ = G_DIR_SEPARATOR;
255 while (*p && G_IS_DIR_SEPARATOR (*p))
256 p++;
259 while (p);
261 g_free (fn);
263 return 0;
267 * g_file_test:
268 * @filename: (type filename): a filename to test in the
269 * GLib file name encoding
270 * @test: bitfield of #GFileTest flags
272 * Returns %TRUE if any of the tests in the bitfield @test are
273 * %TRUE. For example, `(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)`
274 * will return %TRUE if the file exists; the check whether it's a
275 * directory doesn't matter since the existence test is %TRUE. With
276 * the current set of available tests, there's no point passing in
277 * more than one test at a time.
279 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
280 * so for a symbolic link to a regular file g_file_test() will return
281 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
283 * Note, that for a dangling symbolic link g_file_test() will return
284 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
286 * You should never use g_file_test() to test whether it is safe
287 * to perform an operation, because there is always the possibility
288 * of the condition changing before you actually perform the operation.
289 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
290 * to know whether it is safe to write to a file without being
291 * tricked into writing into a different location. It doesn't work!
292 * |[<!-- language="C" -->
293 * // DON'T DO THIS
294 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
296 * fd = g_open (filename, O_WRONLY);
297 * // write to fd
299 * ]|
301 * Another thing to note is that %G_FILE_TEST_EXISTS and
302 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
303 * system call. This usually doesn't matter, but if your program
304 * is setuid or setgid it means that these tests will give you
305 * the answer for the real user ID and group ID, rather than the
306 * effective user ID and group ID.
308 * On Windows, there are no symlinks, so testing for
309 * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
310 * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
311 * its name indicates that it is executable, checking for well-known
312 * extensions and those listed in the `PATHEXT` environment variable.
314 * Returns: whether a test was %TRUE
316 gboolean
317 g_file_test (const gchar *filename,
318 GFileTest test)
320 #ifdef G_OS_WIN32
321 /* stuff missing in std vc6 api */
322 # ifndef INVALID_FILE_ATTRIBUTES
323 # define INVALID_FILE_ATTRIBUTES -1
324 # endif
325 # ifndef FILE_ATTRIBUTE_DEVICE
326 # define FILE_ATTRIBUTE_DEVICE 64
327 # endif
328 int attributes;
329 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
331 if (wfilename == NULL)
332 return FALSE;
334 attributes = GetFileAttributesW (wfilename);
336 g_free (wfilename);
338 if (attributes == INVALID_FILE_ATTRIBUTES)
339 return FALSE;
341 if (test & G_FILE_TEST_EXISTS)
342 return TRUE;
344 if (test & G_FILE_TEST_IS_REGULAR)
346 if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0)
347 return TRUE;
350 if (test & G_FILE_TEST_IS_DIR)
352 if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
353 return TRUE;
356 /* "while" so that we can exit this "loop" with a simple "break" */
357 while (test & G_FILE_TEST_IS_EXECUTABLE)
359 const gchar *lastdot = strrchr (filename, '.');
360 const gchar *pathext = NULL, *p;
361 int extlen;
363 if (lastdot == NULL)
364 break;
366 if (_stricmp (lastdot, ".exe") == 0 ||
367 _stricmp (lastdot, ".cmd") == 0 ||
368 _stricmp (lastdot, ".bat") == 0 ||
369 _stricmp (lastdot, ".com") == 0)
370 return TRUE;
372 /* Check if it is one of the types listed in %PATHEXT% */
374 pathext = g_getenv ("PATHEXT");
375 if (pathext == NULL)
376 break;
378 pathext = g_utf8_casefold (pathext, -1);
380 lastdot = g_utf8_casefold (lastdot, -1);
381 extlen = strlen (lastdot);
383 p = pathext;
384 while (TRUE)
386 const gchar *q = strchr (p, ';');
387 if (q == NULL)
388 q = p + strlen (p);
389 if (extlen == q - p &&
390 memcmp (lastdot, p, extlen) == 0)
392 g_free ((gchar *) pathext);
393 g_free ((gchar *) lastdot);
394 return TRUE;
396 if (*q)
397 p = q + 1;
398 else
399 break;
402 g_free ((gchar *) pathext);
403 g_free ((gchar *) lastdot);
404 break;
407 return FALSE;
408 #else
409 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
410 return TRUE;
412 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
414 if (getuid () != 0)
415 return TRUE;
417 /* For root, on some POSIX systems, access (filename, X_OK)
418 * will succeed even if no executable bits are set on the
419 * file. We fall through to a stat test to avoid that.
422 else
423 test &= ~G_FILE_TEST_IS_EXECUTABLE;
425 if (test & G_FILE_TEST_IS_SYMLINK)
427 struct stat s;
429 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
430 return TRUE;
433 if (test & (G_FILE_TEST_IS_REGULAR |
434 G_FILE_TEST_IS_DIR |
435 G_FILE_TEST_IS_EXECUTABLE))
437 struct stat s;
439 if (stat (filename, &s) == 0)
441 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
442 return TRUE;
444 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
445 return TRUE;
447 /* The extra test for root when access (file, X_OK) succeeds.
449 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
450 ((s.st_mode & S_IXOTH) ||
451 (s.st_mode & S_IXUSR) ||
452 (s.st_mode & S_IXGRP)))
453 return TRUE;
457 return FALSE;
458 #endif
461 G_DEFINE_QUARK (g-file-error-quark, g_file_error)
464 * g_file_error_from_errno:
465 * @err_no: an "errno" value
467 * Gets a #GFileError constant based on the passed-in @err_no.
468 * For example, if you pass in `EEXIST` this function returns
469 * #G_FILE_ERROR_EXIST. Unlike `errno` values, you can portably
470 * assume that all #GFileError values will exist.
472 * Normally a #GFileError value goes into a #GError returned
473 * from a function that manipulates files. So you would use
474 * g_file_error_from_errno() when constructing a #GError.
476 * Returns: #GFileError corresponding to the given @errno
478 GFileError
479 g_file_error_from_errno (gint err_no)
481 switch (err_no)
483 #ifdef EEXIST
484 case EEXIST:
485 return G_FILE_ERROR_EXIST;
486 #endif
488 #ifdef EISDIR
489 case EISDIR:
490 return G_FILE_ERROR_ISDIR;
491 #endif
493 #ifdef EACCES
494 case EACCES:
495 return G_FILE_ERROR_ACCES;
496 #endif
498 #ifdef ENAMETOOLONG
499 case ENAMETOOLONG:
500 return G_FILE_ERROR_NAMETOOLONG;
501 #endif
503 #ifdef ENOENT
504 case ENOENT:
505 return G_FILE_ERROR_NOENT;
506 #endif
508 #ifdef ENOTDIR
509 case ENOTDIR:
510 return G_FILE_ERROR_NOTDIR;
511 #endif
513 #ifdef ENXIO
514 case ENXIO:
515 return G_FILE_ERROR_NXIO;
516 #endif
518 #ifdef ENODEV
519 case ENODEV:
520 return G_FILE_ERROR_NODEV;
521 #endif
523 #ifdef EROFS
524 case EROFS:
525 return G_FILE_ERROR_ROFS;
526 #endif
528 #ifdef ETXTBSY
529 case ETXTBSY:
530 return G_FILE_ERROR_TXTBSY;
531 #endif
533 #ifdef EFAULT
534 case EFAULT:
535 return G_FILE_ERROR_FAULT;
536 #endif
538 #ifdef ELOOP
539 case ELOOP:
540 return G_FILE_ERROR_LOOP;
541 #endif
543 #ifdef ENOSPC
544 case ENOSPC:
545 return G_FILE_ERROR_NOSPC;
546 #endif
548 #ifdef ENOMEM
549 case ENOMEM:
550 return G_FILE_ERROR_NOMEM;
551 #endif
553 #ifdef EMFILE
554 case EMFILE:
555 return G_FILE_ERROR_MFILE;
556 #endif
558 #ifdef ENFILE
559 case ENFILE:
560 return G_FILE_ERROR_NFILE;
561 #endif
563 #ifdef EBADF
564 case EBADF:
565 return G_FILE_ERROR_BADF;
566 #endif
568 #ifdef EINVAL
569 case EINVAL:
570 return G_FILE_ERROR_INVAL;
571 #endif
573 #ifdef EPIPE
574 case EPIPE:
575 return G_FILE_ERROR_PIPE;
576 #endif
578 #ifdef EAGAIN
579 case EAGAIN:
580 return G_FILE_ERROR_AGAIN;
581 #endif
583 #ifdef EINTR
584 case EINTR:
585 return G_FILE_ERROR_INTR;
586 #endif
588 #ifdef EIO
589 case EIO:
590 return G_FILE_ERROR_IO;
591 #endif
593 #ifdef EPERM
594 case EPERM:
595 return G_FILE_ERROR_PERM;
596 #endif
598 #ifdef ENOSYS
599 case ENOSYS:
600 return G_FILE_ERROR_NOSYS;
601 #endif
603 default:
604 return G_FILE_ERROR_FAILED;
608 static char *
609 format_error_message (const gchar *filename,
610 const gchar *format_string,
611 int saved_errno) G_GNUC_FORMAT(2);
613 #pragma GCC diagnostic push
614 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
616 static char *
617 format_error_message (const gchar *filename,
618 const gchar *format_string,
619 int saved_errno)
621 gchar *display_name;
622 gchar *msg;
624 display_name = g_filename_display_name (filename);
625 msg = g_strdup_printf (format_string, display_name, g_strerror (saved_errno));
626 g_free (display_name);
628 return msg;
631 #pragma GCC diagnostic pop
633 /* format string must have two '%s':
635 * - the place for the filename
636 * - the place for the strerror
638 static void
639 set_file_error (GError **error,
640 const gchar *filename,
641 const gchar *format_string,
642 int saved_errno)
644 char *msg = format_error_message (filename, format_string, saved_errno);
646 g_set_error_literal (error, G_FILE_ERROR, g_file_error_from_errno (saved_errno),
647 msg);
648 g_free (msg);
651 static gboolean
652 get_contents_stdio (const gchar *filename,
653 FILE *f,
654 gchar **contents,
655 gsize *length,
656 GError **error)
658 gchar buf[4096];
659 gsize bytes; /* always <= sizeof(buf) */
660 gchar *str = NULL;
661 gsize total_bytes = 0;
662 gsize total_allocated = 0;
663 gchar *tmp;
664 gchar *display_filename;
666 g_assert (f != NULL);
668 while (!feof (f))
670 gint save_errno;
672 bytes = fread (buf, 1, sizeof (buf), f);
673 save_errno = errno;
675 if (total_bytes > G_MAXSIZE - bytes)
676 goto file_too_large;
678 /* Possibility of overflow eliminated above. */
679 while (total_bytes + bytes >= total_allocated)
681 if (str)
683 if (total_allocated > G_MAXSIZE / 2)
684 goto file_too_large;
685 total_allocated *= 2;
687 else
689 total_allocated = MIN (bytes + 1, sizeof (buf));
692 tmp = g_try_realloc (str, total_allocated);
694 if (tmp == NULL)
696 display_filename = g_filename_display_name (filename);
697 g_set_error (error,
698 G_FILE_ERROR,
699 G_FILE_ERROR_NOMEM,
700 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),
701 (gulong) total_allocated,
702 display_filename);
703 g_free (display_filename);
705 goto error;
708 str = tmp;
711 if (ferror (f))
713 display_filename = g_filename_display_name (filename);
714 g_set_error (error,
715 G_FILE_ERROR,
716 g_file_error_from_errno (save_errno),
717 _("Error reading file “%s”: %s"),
718 display_filename,
719 g_strerror (save_errno));
720 g_free (display_filename);
722 goto error;
725 g_assert (str != NULL);
726 memcpy (str + total_bytes, buf, bytes);
728 total_bytes += bytes;
731 fclose (f);
733 if (total_allocated == 0)
735 str = g_new (gchar, 1);
736 total_bytes = 0;
739 str[total_bytes] = '\0';
741 if (length)
742 *length = total_bytes;
744 *contents = str;
746 return TRUE;
748 file_too_large:
749 display_filename = g_filename_display_name (filename);
750 g_set_error (error,
751 G_FILE_ERROR,
752 G_FILE_ERROR_FAILED,
753 _("File “%s” is too large"),
754 display_filename);
755 g_free (display_filename);
757 error:
759 g_free (str);
760 fclose (f);
762 return FALSE;
765 #ifndef G_OS_WIN32
767 static gboolean
768 get_contents_regfile (const gchar *filename,
769 struct stat *stat_buf,
770 gint fd,
771 gchar **contents,
772 gsize *length,
773 GError **error)
775 gchar *buf;
776 gsize bytes_read;
777 gsize size;
778 gsize alloc_size;
779 gchar *display_filename;
781 size = stat_buf->st_size;
783 alloc_size = size + 1;
784 buf = g_try_malloc (alloc_size);
786 if (buf == NULL)
788 display_filename = g_filename_display_name (filename);
789 g_set_error (error,
790 G_FILE_ERROR,
791 G_FILE_ERROR_NOMEM,
792 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),
793 (gulong) alloc_size,
794 display_filename);
795 g_free (display_filename);
796 goto error;
799 bytes_read = 0;
800 while (bytes_read < size)
802 gssize rc;
804 rc = read (fd, buf + bytes_read, size - bytes_read);
806 if (rc < 0)
808 if (errno != EINTR)
810 int save_errno = errno;
812 g_free (buf);
813 display_filename = g_filename_display_name (filename);
814 g_set_error (error,
815 G_FILE_ERROR,
816 g_file_error_from_errno (save_errno),
817 _("Failed to read from file “%s”: %s"),
818 display_filename,
819 g_strerror (save_errno));
820 g_free (display_filename);
821 goto error;
824 else if (rc == 0)
825 break;
826 else
827 bytes_read += rc;
830 buf[bytes_read] = '\0';
832 if (length)
833 *length = bytes_read;
835 *contents = buf;
837 close (fd);
839 return TRUE;
841 error:
843 close (fd);
845 return FALSE;
848 static gboolean
849 get_contents_posix (const gchar *filename,
850 gchar **contents,
851 gsize *length,
852 GError **error)
854 struct stat stat_buf;
855 gint fd;
857 /* O_BINARY useful on Cygwin */
858 fd = open (filename, O_RDONLY|O_BINARY);
860 if (fd < 0)
862 int saved_errno = errno;
863 set_file_error (error,
864 filename,
865 _("Failed to open file “%s”: %s"),
866 saved_errno);
868 return FALSE;
871 /* I don't think this will ever fail, aside from ENOMEM, but. */
872 if (fstat (fd, &stat_buf) < 0)
874 int saved_errno = errno;
875 set_file_error (error,
876 filename,
877 _("Failed to get attributes of file “%s”: fstat() failed: %s"),
878 saved_errno);
879 close (fd);
881 return FALSE;
884 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
886 gboolean retval = get_contents_regfile (filename,
887 &stat_buf,
889 contents,
890 length,
891 error);
893 return retval;
895 else
897 FILE *f;
898 gboolean retval;
900 f = fdopen (fd, "r");
902 if (f == NULL)
904 int saved_errno = errno;
905 set_file_error (error,
906 filename,
907 _("Failed to open file “%s”: fdopen() failed: %s"),
908 saved_errno);
910 return FALSE;
913 retval = get_contents_stdio (filename, f, contents, length, error);
915 return retval;
919 #else /* G_OS_WIN32 */
921 static gboolean
922 get_contents_win32 (const gchar *filename,
923 gchar **contents,
924 gsize *length,
925 GError **error)
927 FILE *f;
928 gboolean retval;
930 f = g_fopen (filename, "rb");
932 if (f == NULL)
934 int saved_errno = errno;
935 set_file_error (error,
936 filename,
937 _("Failed to open file “%s”: %s"),
938 saved_errno);
940 return FALSE;
943 retval = get_contents_stdio (filename, f, contents, length, error);
945 return retval;
948 #endif
951 * g_file_get_contents:
952 * @filename: (type filename): name of a file to read contents from, in the GLib file name encoding
953 * @contents: (out) (array length=length) (element-type guint8): location to store an allocated string, use g_free() to free
954 * the returned string
955 * @length: (nullable): location to store length in bytes of the contents, or %NULL
956 * @error: return location for a #GError, or %NULL
958 * Reads an entire file into allocated memory, with good error
959 * checking.
961 * If the call was successful, it returns %TRUE and sets @contents to the file
962 * contents and @length to the length of the file contents in bytes. The string
963 * stored in @contents will be nul-terminated, so for text files you can pass
964 * %NULL for the @length argument. If the call was not successful, it returns
965 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
966 * codes are those in the #GFileError enumeration. In the error case,
967 * @contents is set to %NULL and @length is set to zero.
969 * Returns: %TRUE on success, %FALSE if an error occurred
971 gboolean
972 g_file_get_contents (const gchar *filename,
973 gchar **contents,
974 gsize *length,
975 GError **error)
977 g_return_val_if_fail (filename != NULL, FALSE);
978 g_return_val_if_fail (contents != NULL, FALSE);
980 *contents = NULL;
981 if (length)
982 *length = 0;
984 #ifdef G_OS_WIN32
985 return get_contents_win32 (filename, contents, length, error);
986 #else
987 return get_contents_posix (filename, contents, length, error);
988 #endif
991 static gboolean
992 rename_file (const char *old_name,
993 const char *new_name,
994 GError **err)
996 errno = 0;
997 if (g_rename (old_name, new_name) == -1)
999 int save_errno = errno;
1000 gchar *display_old_name = g_filename_display_name (old_name);
1001 gchar *display_new_name = g_filename_display_name (new_name);
1003 g_set_error (err,
1004 G_FILE_ERROR,
1005 g_file_error_from_errno (save_errno),
1006 _("Failed to rename file “%s” to “%s”: g_rename() failed: %s"),
1007 display_old_name,
1008 display_new_name,
1009 g_strerror (save_errno));
1011 g_free (display_old_name);
1012 g_free (display_new_name);
1014 return FALSE;
1017 return TRUE;
1020 static gchar *
1021 write_to_temp_file (const gchar *contents,
1022 gssize length,
1023 const gchar *dest_file,
1024 GError **err)
1026 gchar *tmp_name;
1027 gchar *retval;
1028 gint fd;
1030 retval = NULL;
1032 tmp_name = g_strdup_printf ("%s.XXXXXX", dest_file);
1034 errno = 0;
1035 fd = g_mkstemp_full (tmp_name, O_RDWR | O_BINARY, 0666);
1037 if (fd == -1)
1039 int saved_errno = errno;
1040 set_file_error (err,
1041 tmp_name, _("Failed to create file “%s”: %s"),
1042 saved_errno);
1043 goto out;
1046 #ifdef HAVE_FALLOCATE
1047 if (length > 0)
1049 /* We do this on a 'best effort' basis... It may not be supported
1050 * on the underlying filesystem.
1052 (void) fallocate (fd, 0, 0, length);
1054 #endif
1055 while (length > 0)
1057 gssize s;
1059 s = write (fd, contents, length);
1061 if (s < 0)
1063 int saved_errno = errno;
1064 if (saved_errno == EINTR)
1065 continue;
1067 set_file_error (err,
1068 tmp_name, _("Failed to write file “%s”: write() failed: %s"),
1069 saved_errno);
1070 close (fd);
1071 g_unlink (tmp_name);
1073 goto out;
1076 g_assert (s <= length);
1078 contents += s;
1079 length -= s;
1082 #ifdef BTRFS_SUPER_MAGIC
1084 struct statfs buf;
1086 /* On Linux, on btrfs, skip the fsync since rename-over-existing is
1087 * guaranteed to be atomic and this is the only case in which we
1088 * would fsync() anyway.
1091 if (fstatfs (fd, &buf) == 0 && buf.f_type == BTRFS_SUPER_MAGIC)
1092 goto no_fsync;
1094 #endif
1096 #ifdef HAVE_FSYNC
1098 struct stat statbuf;
1100 errno = 0;
1101 /* If the final destination exists and is > 0 bytes, we want to sync the
1102 * newly written file to ensure the data is on disk when we rename over
1103 * the destination. Otherwise if we get a system crash we can lose both
1104 * the new and the old file on some filesystems. (I.E. those that don't
1105 * guarantee the data is written to the disk before the metadata.)
1107 if (g_lstat (dest_file, &statbuf) == 0 && statbuf.st_size > 0 && fsync (fd) != 0)
1109 int saved_errno = errno;
1110 set_file_error (err,
1111 tmp_name, _("Failed to write file “%s”: fsync() failed: %s"),
1112 saved_errno);
1113 close (fd);
1114 g_unlink (tmp_name);
1116 goto out;
1119 #endif
1121 #ifdef BTRFS_SUPER_MAGIC
1122 no_fsync:
1123 #endif
1125 errno = 0;
1126 if (!g_close (fd, err))
1128 g_unlink (tmp_name);
1130 goto out;
1133 retval = g_strdup (tmp_name);
1135 out:
1136 g_free (tmp_name);
1138 return retval;
1142 * g_file_set_contents:
1143 * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1144 * encoding
1145 * @contents: (array length=length) (element-type guint8): string to write to the file
1146 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1147 * @error: return location for a #GError, or %NULL
1149 * Writes all of @contents to a file named @filename, with good error checking.
1150 * If a file called @filename already exists it will be overwritten.
1152 * This write is atomic in the sense that it is first written to a temporary
1153 * file which is then renamed to the final name. Notes:
1155 * - On UNIX, if @filename already exists hard links to @filename will break.
1156 * Also since the file is recreated, existing permissions, access control
1157 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1158 * the link itself will be replaced, not the linked file.
1160 * - On Windows renaming a file will not remove an existing file with the
1161 * new name, so on Windows there is a race condition between the existing
1162 * file being removed and the temporary file being renamed.
1164 * - On Windows there is no way to remove a file that is open to some
1165 * process, or mapped into memory. Thus, this function will fail if
1166 * @filename already exists and is open.
1168 * If the call was successful, it returns %TRUE. If the call was not successful,
1169 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1170 * Possible error codes are those in the #GFileError enumeration.
1172 * Note that the name for the temporary file is constructed by appending up
1173 * to 7 characters to @filename.
1175 * Returns: %TRUE on success, %FALSE if an error occurred
1177 * Since: 2.8
1179 gboolean
1180 g_file_set_contents (const gchar *filename,
1181 const gchar *contents,
1182 gssize length,
1183 GError **error)
1185 gchar *tmp_filename;
1186 gboolean retval;
1187 GError *rename_error = NULL;
1189 g_return_val_if_fail (filename != NULL, FALSE);
1190 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1191 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1192 g_return_val_if_fail (length >= -1, FALSE);
1194 if (length == -1)
1195 length = strlen (contents);
1197 tmp_filename = write_to_temp_file (contents, length, filename, error);
1199 if (!tmp_filename)
1201 retval = FALSE;
1202 goto out;
1205 if (!rename_file (tmp_filename, filename, &rename_error))
1207 #ifndef G_OS_WIN32
1209 g_unlink (tmp_filename);
1210 g_propagate_error (error, rename_error);
1211 retval = FALSE;
1212 goto out;
1214 #else /* G_OS_WIN32 */
1216 /* Renaming failed, but on Windows this may just mean
1217 * the file already exists. So if the target file
1218 * exists, try deleting it and do the rename again.
1220 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1222 g_unlink (tmp_filename);
1223 g_propagate_error (error, rename_error);
1224 retval = FALSE;
1225 goto out;
1228 g_error_free (rename_error);
1230 if (g_unlink (filename) == -1)
1232 int saved_errno = errno;
1233 set_file_error (error,
1234 filename,
1235 _("Existing file “%s” could not be removed: g_unlink() failed: %s"),
1236 saved_errno);
1237 g_unlink (tmp_filename);
1238 retval = FALSE;
1239 goto out;
1242 if (!rename_file (tmp_filename, filename, error))
1244 g_unlink (tmp_filename);
1245 retval = FALSE;
1246 goto out;
1249 #endif
1252 retval = TRUE;
1254 out:
1255 g_free (tmp_filename);
1256 return retval;
1260 * get_tmp_file based on the mkstemp implementation from the GNU C library.
1261 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1263 typedef gint (*GTmpFileCallback) (const gchar *, gint, gint);
1265 static gint
1266 get_tmp_file (gchar *tmpl,
1267 GTmpFileCallback f,
1268 int flags,
1269 int mode)
1271 char *XXXXXX;
1272 int count, fd;
1273 static const char letters[] =
1274 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1275 static const int NLETTERS = sizeof (letters) - 1;
1276 glong value;
1277 GTimeVal tv;
1278 static int counter = 0;
1280 g_return_val_if_fail (tmpl != NULL, -1);
1282 /* find the last occurrence of "XXXXXX" */
1283 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1285 if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1287 errno = EINVAL;
1288 return -1;
1291 /* Get some more or less random data. */
1292 g_get_current_time (&tv);
1293 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1295 for (count = 0; count < 100; value += 7777, ++count)
1297 glong v = value;
1299 /* Fill in the random bits. */
1300 XXXXXX[0] = letters[v % NLETTERS];
1301 v /= NLETTERS;
1302 XXXXXX[1] = letters[v % NLETTERS];
1303 v /= NLETTERS;
1304 XXXXXX[2] = letters[v % NLETTERS];
1305 v /= NLETTERS;
1306 XXXXXX[3] = letters[v % NLETTERS];
1307 v /= NLETTERS;
1308 XXXXXX[4] = letters[v % NLETTERS];
1309 v /= NLETTERS;
1310 XXXXXX[5] = letters[v % NLETTERS];
1312 fd = f (tmpl, flags, mode);
1314 if (fd >= 0)
1315 return fd;
1316 else if (errno != EEXIST)
1317 /* Any other error will apply also to other names we might
1318 * try, and there are 2^32 or so of them, so give up now.
1320 return -1;
1323 /* We got out of the loop because we ran out of combinations to try. */
1324 errno = EEXIST;
1325 return -1;
1328 /* Some GTmpFileCallback implementations.
1330 * Note: we cannot use open() or g_open() directly because even though
1331 * they appear compatible, they may be vararg functions and calling
1332 * varargs functions through a non-varargs type is undefined.
1334 static gint
1335 wrap_g_mkdir (const gchar *filename,
1336 int flags G_GNUC_UNUSED,
1337 int mode)
1339 /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1340 return g_mkdir (filename, mode);
1343 static gint
1344 wrap_g_open (const gchar *filename,
1345 int flags,
1346 int mode)
1348 return g_open (filename, flags, mode);
1352 * g_mkdtemp_full: (skip)
1353 * @tmpl: (type filename): template directory name
1354 * @mode: permissions to create the temporary directory with
1356 * Creates a temporary directory. See the mkdtemp() documentation
1357 * on most UNIX-like systems.
1359 * The parameter is a string that should follow the rules for
1360 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1361 * g_mkdtemp_full() is slightly more flexible than mkdtemp() in that the
1362 * sequence does not have to occur at the very end of the template
1363 * and you can pass a @mode. The X string will be modified to form
1364 * the name of a directory that didn't exist. The string should be
1365 * in the GLib file name encoding. Most importantly, on Windows it
1366 * should be in UTF-8.
1368 * If you are going to be creating a temporary directory inside the
1369 * directory returned by g_get_tmp_dir(), you might want to use
1370 * g_dir_make_tmp() instead.
1372 * Returns: (nullable) (type filename): A pointer to @tmpl, which has been
1373 * modified to hold the directory name. In case of errors, %NULL is
1374 * returned, and %errno will be set.
1376 * Since: 2.30
1378 gchar *
1379 g_mkdtemp_full (gchar *tmpl,
1380 gint mode)
1382 if (get_tmp_file (tmpl, wrap_g_mkdir, 0, mode) == -1)
1383 return NULL;
1384 else
1385 return tmpl;
1389 * g_mkdtemp: (skip)
1390 * @tmpl: (type filename): template directory name
1392 * Creates a temporary directory. See the mkdtemp() documentation
1393 * on most UNIX-like systems.
1395 * The parameter is a string that should follow the rules for
1396 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1397 * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1398 * sequence does not have to occur at the very end of the template.
1399 * The X string will be modified to form the name of a directory that
1400 * didn't exist.
1401 * The string should be in the GLib file name encoding. Most importantly,
1402 * on Windows it should be in UTF-8.
1404 * If you are going to be creating a temporary directory inside the
1405 * directory returned by g_get_tmp_dir(), you might want to use
1406 * g_dir_make_tmp() instead.
1408 * Returns: (nullable) (type filename): A pointer to @tmpl, which has been
1409 * modified to hold the directory name. In case of errors, %NULL is
1410 * returned and %errno will be set.
1412 * Since: 2.30
1414 gchar *
1415 g_mkdtemp (gchar *tmpl)
1417 return g_mkdtemp_full (tmpl, 0700);
1421 * g_mkstemp_full: (skip)
1422 * @tmpl: (type filename): template filename
1423 * @flags: flags to pass to an open() call in addition to O_EXCL
1424 * and O_CREAT, which are passed automatically
1425 * @mode: permissions to create the temporary file with
1427 * Opens a temporary file. See the mkstemp() documentation
1428 * on most UNIX-like systems.
1430 * The parameter is a string that should follow the rules for
1431 * mkstemp() templates, i.e. contain the string "XXXXXX".
1432 * g_mkstemp_full() is slightly more flexible than mkstemp()
1433 * in that the sequence does not have to occur at the very end of the
1434 * template and you can pass a @mode and additional @flags. The X
1435 * string will be modified to form the name of a file that didn't exist.
1436 * The string should be in the GLib file name encoding. Most importantly,
1437 * on Windows it should be in UTF-8.
1439 * Returns: A file handle (as from open()) to the file
1440 * opened for reading and writing. The file handle should be
1441 * closed with close(). In case of errors, -1 is returned
1442 * and %errno will be set.
1444 * Since: 2.22
1446 gint
1447 g_mkstemp_full (gchar *tmpl,
1448 gint flags,
1449 gint mode)
1451 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1452 return get_tmp_file (tmpl, wrap_g_open,
1453 flags | O_CREAT | O_EXCL, mode);
1457 * g_mkstemp: (skip)
1458 * @tmpl: (type filename): template filename
1460 * Opens a temporary file. See the mkstemp() documentation
1461 * on most UNIX-like systems.
1463 * The parameter is a string that should follow the rules for
1464 * mkstemp() templates, i.e. contain the string "XXXXXX".
1465 * g_mkstemp() is slightly more flexible than mkstemp() in that the
1466 * sequence does not have to occur at the very end of the template.
1467 * The X string will be modified to form the name of a file that
1468 * didn't exist. The string should be in the GLib file name encoding.
1469 * Most importantly, on Windows it should be in UTF-8.
1471 * Returns: A file handle (as from open()) to the file
1472 * opened for reading and writing. The file is opened in binary
1473 * mode on platforms where there is a difference. The file handle
1474 * should be closed with close(). In case of errors, -1 is
1475 * returned and %errno will be set.
1477 gint
1478 g_mkstemp (gchar *tmpl)
1480 return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1483 static gint
1484 g_get_tmp_name (const gchar *tmpl,
1485 gchar **name_used,
1486 GTmpFileCallback f,
1487 gint flags,
1488 gint mode,
1489 GError **error)
1491 int retval;
1492 const char *tmpdir;
1493 const char *sep;
1494 char *fulltemplate;
1495 const char *slash;
1497 if (tmpl == NULL)
1498 tmpl = ".XXXXXX";
1500 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1501 #ifdef G_OS_WIN32
1502 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1503 #endif
1506 gchar *display_tmpl = g_filename_display_name (tmpl);
1507 char c[2];
1508 c[0] = *slash;
1509 c[1] = '\0';
1511 g_set_error (error,
1512 G_FILE_ERROR,
1513 G_FILE_ERROR_FAILED,
1514 _("Template “%s” invalid, should not contain a “%s”"),
1515 display_tmpl, c);
1516 g_free (display_tmpl);
1518 return -1;
1521 if (strstr (tmpl, "XXXXXX") == NULL)
1523 gchar *display_tmpl = g_filename_display_name (tmpl);
1524 g_set_error (error,
1525 G_FILE_ERROR,
1526 G_FILE_ERROR_FAILED,
1527 _("Template “%s” doesn’t contain XXXXXX"),
1528 display_tmpl);
1529 g_free (display_tmpl);
1530 return -1;
1533 tmpdir = g_get_tmp_dir ();
1535 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1536 sep = "";
1537 else
1538 sep = G_DIR_SEPARATOR_S;
1540 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1542 retval = get_tmp_file (fulltemplate, f, flags, mode);
1543 if (retval == -1)
1545 int saved_errno = errno;
1546 set_file_error (error,
1547 fulltemplate,
1548 _("Failed to create file “%s”: %s"),
1549 saved_errno);
1550 g_free (fulltemplate);
1551 return -1;
1554 *name_used = fulltemplate;
1556 return retval;
1560 * g_file_open_tmp:
1561 * @tmpl: (type filename) (nullable): Template for file name, as in
1562 * g_mkstemp(), basename only, or %NULL for a default template
1563 * @name_used: (out) (type filename): location to store actual name used,
1564 * or %NULL
1565 * @error: return location for a #GError
1567 * Opens a file for writing in the preferred directory for temporary
1568 * files (as returned by g_get_tmp_dir()).
1570 * @tmpl should be a string in the GLib file name encoding containing
1571 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1572 * However, unlike these functions, the template should only be a
1573 * basename, no directory components are allowed. If template is
1574 * %NULL, a default template is used.
1576 * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
1577 * modified, and might thus be a read-only literal string.
1579 * Upon success, and if @name_used is non-%NULL, the actual name used
1580 * is returned in @name_used. This string should be freed with g_free()
1581 * when not needed any longer. The returned name is in the GLib file
1582 * name encoding.
1584 * Returns: A file handle (as from open()) to the file opened for
1585 * reading and writing. The file is opened in binary mode on platforms
1586 * where there is a difference. The file handle should be closed with
1587 * close(). In case of errors, -1 is returned and @error will be set.
1589 gint
1590 g_file_open_tmp (const gchar *tmpl,
1591 gchar **name_used,
1592 GError **error)
1594 gchar *fulltemplate;
1595 gint result;
1597 result = g_get_tmp_name (tmpl, &fulltemplate,
1598 wrap_g_open,
1599 O_CREAT | O_EXCL | O_RDWR | O_BINARY,
1600 0600,
1601 error);
1602 if (result != -1)
1604 if (name_used)
1605 *name_used = fulltemplate;
1606 else
1607 g_free (fulltemplate);
1610 return result;
1614 * g_dir_make_tmp:
1615 * @tmpl: (type filename) (nullable): Template for directory name,
1616 * as in g_mkdtemp(), basename only, or %NULL for a default template
1617 * @error: return location for a #GError
1619 * Creates a subdirectory in the preferred directory for temporary
1620 * files (as returned by g_get_tmp_dir()).
1622 * @tmpl should be a string in the GLib file name encoding containing
1623 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1624 * However, unlike these functions, the template should only be a
1625 * basename, no directory components are allowed. If template is
1626 * %NULL, a default template is used.
1628 * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
1629 * modified, and might thus be a read-only literal string.
1631 * Returns: (type filename): The actual name used. This string
1632 * should be freed with g_free() when not needed any longer and is
1633 * is in the GLib file name encoding. In case of errors, %NULL is
1634 * returned and @error will be set.
1636 * Since: 2.30
1638 gchar *
1639 g_dir_make_tmp (const gchar *tmpl,
1640 GError **error)
1642 gchar *fulltemplate;
1644 if (g_get_tmp_name (tmpl, &fulltemplate, wrap_g_mkdir, 0, 0700, error) == -1)
1645 return NULL;
1646 else
1647 return fulltemplate;
1650 static gchar *
1651 g_build_path_va (const gchar *separator,
1652 const gchar *first_element,
1653 va_list *args,
1654 gchar **str_array)
1656 GString *result;
1657 gint separator_len = strlen (separator);
1658 gboolean is_first = TRUE;
1659 gboolean have_leading = FALSE;
1660 const gchar *single_element = NULL;
1661 const gchar *next_element;
1662 const gchar *last_trailing = NULL;
1663 gint i = 0;
1665 result = g_string_new (NULL);
1667 if (str_array)
1668 next_element = str_array[i++];
1669 else
1670 next_element = first_element;
1672 while (TRUE)
1674 const gchar *element;
1675 const gchar *start;
1676 const gchar *end;
1678 if (next_element)
1680 element = next_element;
1681 if (str_array)
1682 next_element = str_array[i++];
1683 else
1684 next_element = va_arg (*args, gchar *);
1686 else
1687 break;
1689 /* Ignore empty elements */
1690 if (!*element)
1691 continue;
1693 start = element;
1695 if (separator_len)
1697 while (strncmp (start, separator, separator_len) == 0)
1698 start += separator_len;
1701 end = start + strlen (start);
1703 if (separator_len)
1705 while (end >= start + separator_len &&
1706 strncmp (end - separator_len, separator, separator_len) == 0)
1707 end -= separator_len;
1709 last_trailing = end;
1710 while (last_trailing >= element + separator_len &&
1711 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1712 last_trailing -= separator_len;
1714 if (!have_leading)
1716 /* If the leading and trailing separator strings are in the
1717 * same element and overlap, the result is exactly that element
1719 if (last_trailing <= start)
1720 single_element = element;
1722 g_string_append_len (result, element, start - element);
1723 have_leading = TRUE;
1725 else
1726 single_element = NULL;
1729 if (end == start)
1730 continue;
1732 if (!is_first)
1733 g_string_append (result, separator);
1735 g_string_append_len (result, start, end - start);
1736 is_first = FALSE;
1739 if (single_element)
1741 g_string_free (result, TRUE);
1742 return g_strdup (single_element);
1744 else
1746 if (last_trailing)
1747 g_string_append (result, last_trailing);
1749 return g_string_free (result, FALSE);
1754 * g_build_pathv:
1755 * @separator: a string used to separator the elements of the path.
1756 * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
1757 * array of strings containing the path elements.
1759 * Behaves exactly like g_build_path(), but takes the path elements
1760 * as a string array, instead of varargs. This function is mainly
1761 * meant for language bindings.
1763 * Returns: (type filename): a newly-allocated string that must be freed
1764 * with g_free().
1766 * Since: 2.8
1768 gchar *
1769 g_build_pathv (const gchar *separator,
1770 gchar **args)
1772 if (!args)
1773 return NULL;
1775 return g_build_path_va (separator, NULL, NULL, args);
1780 * g_build_path:
1781 * @separator: (type filename): a string used to separator the elements of the path.
1782 * @first_element: (type filename): the first element in the path
1783 * @...: remaining elements in path, terminated by %NULL
1785 * Creates a path from a series of elements using @separator as the
1786 * separator between elements. At the boundary between two elements,
1787 * any trailing occurrences of separator in the first element, or
1788 * leading occurrences of separator in the second element are removed
1789 * and exactly one copy of the separator is inserted.
1791 * Empty elements are ignored.
1793 * The number of leading copies of the separator on the result is
1794 * the same as the number of leading copies of the separator on
1795 * the first non-empty element.
1797 * The number of trailing copies of the separator on the result is
1798 * the same as the number of trailing copies of the separator on
1799 * the last non-empty element. (Determination of the number of
1800 * trailing copies is done without stripping leading copies, so
1801 * if the separator is `ABA`, then `ABABA` has 1 trailing copy.)
1803 * However, if there is only a single non-empty element, and there
1804 * are no characters in that element not part of the leading or
1805 * trailing separators, then the result is exactly the original value
1806 * of that element.
1808 * Other than for determination of the number of leading and trailing
1809 * copies of the separator, elements consisting only of copies
1810 * of the separator are ignored.
1812 * Returns: (type filename): a newly-allocated string that must be freed with
1813 * g_free().
1815 gchar *
1816 g_build_path (const gchar *separator,
1817 const gchar *first_element,
1818 ...)
1820 gchar *str;
1821 va_list args;
1823 g_return_val_if_fail (separator != NULL, NULL);
1825 va_start (args, first_element);
1826 str = g_build_path_va (separator, first_element, &args, NULL);
1827 va_end (args);
1829 return str;
1832 #ifdef G_OS_WIN32
1834 static gchar *
1835 g_build_pathname_va (const gchar *first_element,
1836 va_list *args,
1837 gchar **str_array)
1839 /* Code copied from g_build_pathv(), and modified to use two
1840 * alternative single-character separators.
1842 GString *result;
1843 gboolean is_first = TRUE;
1844 gboolean have_leading = FALSE;
1845 const gchar *single_element = NULL;
1846 const gchar *next_element;
1847 const gchar *last_trailing = NULL;
1848 gchar current_separator = '\\';
1849 gint i = 0;
1851 result = g_string_new (NULL);
1853 if (str_array)
1854 next_element = str_array[i++];
1855 else
1856 next_element = first_element;
1858 while (TRUE)
1860 const gchar *element;
1861 const gchar *start;
1862 const gchar *end;
1864 if (next_element)
1866 element = next_element;
1867 if (str_array)
1868 next_element = str_array[i++];
1869 else
1870 next_element = va_arg (*args, gchar *);
1872 else
1873 break;
1875 /* Ignore empty elements */
1876 if (!*element)
1877 continue;
1879 start = element;
1881 if (TRUE)
1883 while (start &&
1884 (*start == '\\' || *start == '/'))
1886 current_separator = *start;
1887 start++;
1891 end = start + strlen (start);
1893 if (TRUE)
1895 while (end >= start + 1 &&
1896 (end[-1] == '\\' || end[-1] == '/'))
1898 current_separator = end[-1];
1899 end--;
1902 last_trailing = end;
1903 while (last_trailing >= element + 1 &&
1904 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1905 last_trailing--;
1907 if (!have_leading)
1909 /* If the leading and trailing separator strings are in the
1910 * same element and overlap, the result is exactly that element
1912 if (last_trailing <= start)
1913 single_element = element;
1915 g_string_append_len (result, element, start - element);
1916 have_leading = TRUE;
1918 else
1919 single_element = NULL;
1922 if (end == start)
1923 continue;
1925 if (!is_first)
1926 g_string_append_len (result, &current_separator, 1);
1928 g_string_append_len (result, start, end - start);
1929 is_first = FALSE;
1932 if (single_element)
1934 g_string_free (result, TRUE);
1935 return g_strdup (single_element);
1937 else
1939 if (last_trailing)
1940 g_string_append (result, last_trailing);
1942 return g_string_free (result, FALSE);
1946 #endif
1949 * g_build_filenamev:
1950 * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
1951 * array of strings containing the path elements.
1953 * Behaves exactly like g_build_filename(), but takes the path elements
1954 * as a string array, instead of varargs. This function is mainly
1955 * meant for language bindings.
1957 * Returns: (type filename): a newly-allocated string that must be freed
1958 * with g_free().
1960 * Since: 2.8
1962 gchar *
1963 g_build_filenamev (gchar **args)
1965 gchar *str;
1967 #ifndef G_OS_WIN32
1968 str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1969 #else
1970 str = g_build_pathname_va (NULL, NULL, args);
1971 #endif
1973 return str;
1977 * g_build_filename:
1978 * @first_element: (type filename): the first element in the path
1979 * @...: remaining elements in path, terminated by %NULL
1981 * Creates a filename from a series of elements using the correct
1982 * separator for filenames.
1984 * On Unix, this function behaves identically to `g_build_path
1985 * (G_DIR_SEPARATOR_S, first_element, ....)`.
1987 * On Windows, it takes into account that either the backslash
1988 * (`\` or slash (`/`) can be used as separator in filenames, but
1989 * otherwise behaves as on UNIX. When file pathname separators need
1990 * to be inserted, the one that last previously occurred in the
1991 * parameters (reading from left to right) is used.
1993 * No attempt is made to force the resulting filename to be an absolute
1994 * path. If the first element is a relative path, the result will
1995 * be a relative path.
1997 * Returns: (type filename): a newly-allocated string that must be freed with
1998 * g_free().
2000 gchar *
2001 g_build_filename (const gchar *first_element,
2002 ...)
2004 gchar *str;
2005 va_list args;
2007 va_start (args, first_element);
2008 #ifndef G_OS_WIN32
2009 str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
2010 #else
2011 str = g_build_pathname_va (first_element, &args, NULL);
2012 #endif
2013 va_end (args);
2015 return str;
2019 * g_file_read_link:
2020 * @filename: (type filename): the symbolic link
2021 * @error: return location for a #GError
2023 * Reads the contents of the symbolic link @filename like the POSIX
2024 * readlink() function. The returned string is in the encoding used
2025 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
2027 * Returns: (type filename): A newly-allocated string with the contents of
2028 * the symbolic link, or %NULL if an error occurred.
2030 * Since: 2.4
2032 gchar *
2033 g_file_read_link (const gchar *filename,
2034 GError **error)
2036 #ifdef HAVE_READLINK
2037 gchar *buffer;
2038 size_t size;
2039 ssize_t read_size;
2041 size = 256;
2042 buffer = g_malloc (size);
2044 while (TRUE)
2046 read_size = readlink (filename, buffer, size);
2047 if (read_size < 0)
2049 int saved_errno = errno;
2050 set_file_error (error,
2051 filename,
2052 _("Failed to read the symbolic link “%s”: %s"),
2053 saved_errno);
2054 g_free (buffer);
2055 return NULL;
2058 if ((size_t) read_size < size)
2060 buffer[read_size] = 0;
2061 return buffer;
2064 size *= 2;
2065 buffer = g_realloc (buffer, size);
2067 #else
2068 g_set_error_literal (error,
2069 G_FILE_ERROR,
2070 G_FILE_ERROR_INVAL,
2071 _("Symbolic links not supported"));
2073 return NULL;
2074 #endif
2078 * g_path_is_absolute:
2079 * @file_name: (type filename): a file name
2081 * Returns %TRUE if the given @file_name is an absolute file name.
2082 * Note that this is a somewhat vague concept on Windows.
2084 * On POSIX systems, an absolute file name is well-defined. It always
2085 * starts from the single root directory. For example "/usr/local".
2087 * On Windows, the concepts of current drive and drive-specific
2088 * current directory introduce vagueness. This function interprets as
2089 * an absolute file name one that either begins with a directory
2090 * separator such as "\Users\tml" or begins with the root on a drive,
2091 * for example "C:\Windows". The first case also includes UNC paths
2092 * such as "\\myserver\docs\foo". In all cases, either slashes or
2093 * backslashes are accepted.
2095 * Note that a file name relative to the current drive root does not
2096 * truly specify a file uniquely over time and across processes, as
2097 * the current drive is a per-process value and can be changed.
2099 * File names relative the current directory on some specific drive,
2100 * such as "D:foo/bar", are not interpreted as absolute by this
2101 * function, but they obviously are not relative to the normal current
2102 * directory as returned by getcwd() or g_get_current_dir()
2103 * either. Such paths should be avoided, or need to be handled using
2104 * Windows-specific code.
2106 * Returns: %TRUE if @file_name is absolute
2108 gboolean
2109 g_path_is_absolute (const gchar *file_name)
2111 g_return_val_if_fail (file_name != NULL, FALSE);
2113 if (G_IS_DIR_SEPARATOR (file_name[0]))
2114 return TRUE;
2116 #ifdef G_OS_WIN32
2117 /* Recognize drive letter on native Windows */
2118 if (g_ascii_isalpha (file_name[0]) &&
2119 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
2120 return TRUE;
2121 #endif
2123 return FALSE;
2127 * g_path_skip_root:
2128 * @file_name: (type filename): a file name
2130 * Returns a pointer into @file_name after the root component,
2131 * i.e. after the "/" in UNIX or "C:\" under Windows. If @file_name
2132 * is not an absolute path it returns %NULL.
2134 * Returns: (type filename) (nullable): a pointer into @file_name after the
2135 * root component
2137 const gchar *
2138 g_path_skip_root (const gchar *file_name)
2140 g_return_val_if_fail (file_name != NULL, NULL);
2142 #ifdef G_PLATFORM_WIN32
2143 /* Skip \\server\share or //server/share */
2144 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2145 G_IS_DIR_SEPARATOR (file_name[1]) &&
2146 file_name[2] &&
2147 !G_IS_DIR_SEPARATOR (file_name[2]))
2149 gchar *p;
2150 p = strchr (file_name + 2, G_DIR_SEPARATOR);
2152 #ifdef G_OS_WIN32
2154 gchar *q;
2156 q = strchr (file_name + 2, '/');
2157 if (p == NULL || (q != NULL && q < p))
2158 p = q;
2160 #endif
2162 if (p && p > file_name + 2 && p[1])
2164 file_name = p + 1;
2166 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
2167 file_name++;
2169 /* Possibly skip a backslash after the share name */
2170 if (G_IS_DIR_SEPARATOR (file_name[0]))
2171 file_name++;
2173 return (gchar *)file_name;
2176 #endif
2178 /* Skip initial slashes */
2179 if (G_IS_DIR_SEPARATOR (file_name[0]))
2181 while (G_IS_DIR_SEPARATOR (file_name[0]))
2182 file_name++;
2183 return (gchar *)file_name;
2186 #ifdef G_OS_WIN32
2187 /* Skip X:\ */
2188 if (g_ascii_isalpha (file_name[0]) &&
2189 file_name[1] == ':' &&
2190 G_IS_DIR_SEPARATOR (file_name[2]))
2191 return (gchar *)file_name + 3;
2192 #endif
2194 return NULL;
2198 * g_basename:
2199 * @file_name: (type filename): the name of the file
2201 * Gets the name of the file without any leading directory
2202 * components. It returns a pointer into the given file name
2203 * string.
2205 * Returns: (type filename): the name of the file without any leading
2206 * directory components
2208 * Deprecated:2.2: Use g_path_get_basename() instead, but notice
2209 * that g_path_get_basename() allocates new memory for the
2210 * returned string, unlike this function which returns a pointer
2211 * into the argument.
2213 const gchar *
2214 g_basename (const gchar *file_name)
2216 gchar *base;
2218 g_return_val_if_fail (file_name != NULL, NULL);
2220 base = strrchr (file_name, G_DIR_SEPARATOR);
2222 #ifdef G_OS_WIN32
2224 gchar *q;
2225 q = strrchr (file_name, '/');
2226 if (base == NULL || (q != NULL && q > base))
2227 base = q;
2229 #endif
2231 if (base)
2232 return base + 1;
2234 #ifdef G_OS_WIN32
2235 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2236 return (gchar*) file_name + 2;
2237 #endif
2239 return (gchar*) file_name;
2243 * g_path_get_basename:
2244 * @file_name: (type filename): the name of the file
2246 * Gets the last component of the filename.
2248 * If @file_name ends with a directory separator it gets the component
2249 * before the last slash. If @file_name consists only of directory
2250 * separators (and on Windows, possibly a drive letter), a single
2251 * separator is returned. If @file_name is empty, it gets ".".
2253 * Returns: (type filename): a newly allocated string containing the last
2254 * component of the filename
2256 gchar *
2257 g_path_get_basename (const gchar *file_name)
2259 gssize base;
2260 gssize last_nonslash;
2261 gsize len;
2262 gchar *retval;
2264 g_return_val_if_fail (file_name != NULL, NULL);
2266 if (file_name[0] == '\0')
2267 return g_strdup (".");
2269 last_nonslash = strlen (file_name) - 1;
2271 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
2272 last_nonslash--;
2274 if (last_nonslash == -1)
2275 /* string only containing slashes */
2276 return g_strdup (G_DIR_SEPARATOR_S);
2278 #ifdef G_OS_WIN32
2279 if (last_nonslash == 1 &&
2280 g_ascii_isalpha (file_name[0]) &&
2281 file_name[1] == ':')
2282 /* string only containing slashes and a drive */
2283 return g_strdup (G_DIR_SEPARATOR_S);
2284 #endif
2285 base = last_nonslash;
2287 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
2288 base--;
2290 #ifdef G_OS_WIN32
2291 if (base == -1 &&
2292 g_ascii_isalpha (file_name[0]) &&
2293 file_name[1] == ':')
2294 base = 1;
2295 #endif /* G_OS_WIN32 */
2297 len = last_nonslash - base;
2298 retval = g_malloc (len + 1);
2299 memcpy (retval, file_name + base + 1, len);
2300 retval [len] = '\0';
2302 return retval;
2306 * g_dirname:
2307 * @file_name: (type filename): the name of the file
2309 * Gets the directory components of a file name.
2311 * If the file name has no directory components "." is returned.
2312 * The returned string should be freed when no longer needed.
2314 * Returns: (type filename): the directory components of the file
2316 * Deprecated: use g_path_get_dirname() instead
2320 * g_path_get_dirname:
2321 * @file_name: (type filename): the name of the file
2323 * Gets the directory components of a file name.
2325 * If the file name has no directory components "." is returned.
2326 * The returned string should be freed when no longer needed.
2328 * Returns: (type filename): the directory components of the file
2330 gchar *
2331 g_path_get_dirname (const gchar *file_name)
2333 gchar *base;
2334 gsize len;
2336 g_return_val_if_fail (file_name != NULL, NULL);
2338 base = strrchr (file_name, G_DIR_SEPARATOR);
2340 #ifdef G_OS_WIN32
2342 gchar *q;
2343 q = strrchr (file_name, '/');
2344 if (base == NULL || (q != NULL && q > base))
2345 base = q;
2347 #endif
2349 if (!base)
2351 #ifdef G_OS_WIN32
2352 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2354 gchar drive_colon_dot[4];
2356 drive_colon_dot[0] = file_name[0];
2357 drive_colon_dot[1] = ':';
2358 drive_colon_dot[2] = '.';
2359 drive_colon_dot[3] = '\0';
2361 return g_strdup (drive_colon_dot);
2363 #endif
2364 return g_strdup (".");
2367 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
2368 base--;
2370 #ifdef G_OS_WIN32
2371 /* base points to the char before the last slash.
2373 * In case file_name is the root of a drive (X:\) or a child of the
2374 * root of a drive (X:\foo), include the slash.
2376 * In case file_name is the root share of an UNC path
2377 * (\\server\share), add a slash, returning \\server\share\ .
2379 * In case file_name is a direct child of a share in an UNC path
2380 * (\\server\share\foo), include the slash after the share name,
2381 * returning \\server\share\ .
2383 if (base == file_name + 1 &&
2384 g_ascii_isalpha (file_name[0]) &&
2385 file_name[1] == ':')
2386 base++;
2387 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2388 G_IS_DIR_SEPARATOR (file_name[1]) &&
2389 file_name[2] &&
2390 !G_IS_DIR_SEPARATOR (file_name[2]) &&
2391 base >= file_name + 2)
2393 const gchar *p = file_name + 2;
2394 while (*p && !G_IS_DIR_SEPARATOR (*p))
2395 p++;
2396 if (p == base + 1)
2398 len = (guint) strlen (file_name) + 1;
2399 base = g_new (gchar, len + 1);
2400 strcpy (base, file_name);
2401 base[len-1] = G_DIR_SEPARATOR;
2402 base[len] = 0;
2403 return base;
2405 if (G_IS_DIR_SEPARATOR (*p))
2407 p++;
2408 while (*p && !G_IS_DIR_SEPARATOR (*p))
2409 p++;
2410 if (p == base + 1)
2411 base++;
2414 #endif
2416 len = (guint) 1 + base - file_name;
2417 base = g_new (gchar, len + 1);
2418 memmove (base, file_name, len);
2419 base[len] = 0;
2421 return base;
2424 #if defined(MAXPATHLEN)
2425 #define G_PATH_LENGTH MAXPATHLEN
2426 #elif defined(PATH_MAX)
2427 #define G_PATH_LENGTH PATH_MAX
2428 #elif defined(_PC_PATH_MAX)
2429 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
2430 #else
2431 #define G_PATH_LENGTH 2048
2432 #endif
2435 * g_get_current_dir:
2437 * Gets the current directory.
2439 * The returned string should be freed when no longer needed.
2440 * The encoding of the returned string is system defined.
2441 * On Windows, it is always UTF-8.
2443 * Since GLib 2.40, this function will return the value of the "PWD"
2444 * environment variable if it is set and it happens to be the same as
2445 * the current directory. This can make a difference in the case that
2446 * the current directory is the target of a symbolic link.
2448 * Returns: (type filename): the current directory
2450 gchar *
2451 g_get_current_dir (void)
2453 #ifdef G_OS_WIN32
2455 gchar *dir = NULL;
2456 wchar_t dummy[2], *wdir;
2457 int len;
2459 len = GetCurrentDirectoryW (2, dummy);
2460 wdir = g_new (wchar_t, len);
2462 if (GetCurrentDirectoryW (len, wdir) == len - 1)
2463 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
2465 g_free (wdir);
2467 if (dir == NULL)
2468 dir = g_strdup ("\\");
2470 return dir;
2472 #else
2473 const gchar *pwd;
2474 gchar *buffer = NULL;
2475 gchar *dir = NULL;
2476 static gulong max_len = 0;
2477 struct stat pwdbuf, dotbuf;
2479 pwd = g_getenv ("PWD");
2480 if (pwd != NULL &&
2481 g_stat (".", &dotbuf) == 0 && g_stat (pwd, &pwdbuf) == 0 &&
2482 dotbuf.st_dev == pwdbuf.st_dev && dotbuf.st_ino == pwdbuf.st_ino)
2483 return g_strdup (pwd);
2485 if (max_len == 0)
2486 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
2488 while (max_len < G_MAXULONG / 2)
2490 g_free (buffer);
2491 buffer = g_new (gchar, max_len + 1);
2492 *buffer = 0;
2493 dir = getcwd (buffer, max_len);
2495 if (dir || errno != ERANGE)
2496 break;
2498 max_len *= 2;
2501 if (!dir || !*buffer)
2503 /* hm, should we g_error() out here?
2504 * this can happen if e.g. "./" has mode \0000
2506 buffer[0] = G_DIR_SEPARATOR;
2507 buffer[1] = 0;
2510 dir = g_strdup (buffer);
2511 g_free (buffer);
2513 return dir;
2515 #endif /* !G_OS_WIN32 */
2519 /* NOTE : Keep this part last to ensure nothing in this file uses thn
2520 * below binary compatibility versions.
2522 #if defined (G_OS_WIN32) && !defined (_WIN64)
2524 /* Binary compatibility versions. Will be called by code compiled
2525 * against quite old (pre-2.8, I think) headers only, not from more
2526 * recently compiled code.
2529 #undef g_file_test
2531 gboolean
2532 g_file_test (const gchar *filename,
2533 GFileTest test)
2535 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
2536 gboolean retval;
2538 if (utf8_filename == NULL)
2539 return FALSE;
2541 retval = g_file_test_utf8 (utf8_filename, test);
2543 g_free (utf8_filename);
2545 return retval;
2548 #undef g_file_get_contents
2550 gboolean
2551 g_file_get_contents (const gchar *filename,
2552 gchar **contents,
2553 gsize *length,
2554 GError **error)
2556 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
2557 gboolean retval;
2559 if (utf8_filename == NULL)
2560 return FALSE;
2562 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
2564 g_free (utf8_filename);
2566 return retval;
2569 #undef g_mkstemp
2571 static gint
2572 wrap_libc_open (const gchar *filename,
2573 int flags,
2574 int mode)
2576 return open (filename, flags, mode);
2579 gint
2580 g_mkstemp (gchar *tmpl)
2582 /* This is the backward compatibility system codepage version,
2583 * thus use normal open().
2585 return get_tmp_file (tmpl, wrap_libc_open,
2586 O_RDWR | O_CREAT | O_EXCL, 0600);
2589 #undef g_file_open_tmp
2591 gint
2592 g_file_open_tmp (const gchar *tmpl,
2593 gchar **name_used,
2594 GError **error)
2596 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
2597 gchar *utf8_name_used;
2598 gint retval;
2600 if (utf8_tmpl == NULL)
2601 return -1;
2603 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
2605 if (retval == -1)
2606 return -1;
2608 if (name_used)
2609 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
2611 g_free (utf8_name_used);
2613 return retval;
2616 #undef g_get_current_dir
2618 gchar *
2619 g_get_current_dir (void)
2621 gchar *utf8_dir = g_get_current_dir_utf8 ();
2622 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
2623 g_free (utf8_dir);
2624 return dir;
2627 #endif