add 2.36 index to gobject docs
[glib.git] / glib / gfileutils.c
blob3c1b135ef7ffa9ef0da190542a5ad94fd048f2d6
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 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 * Boston, MA 02111-1307, USA.
21 #include "config.h"
22 #include "glibconfig.h"
24 #include <sys/stat.h>
25 #ifdef HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <string.h>
32 #include <errno.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <fcntl.h>
36 #include <stdlib.h>
38 #ifdef G_OS_WIN32
39 #include <windows.h>
40 #include <io.h>
41 #endif /* G_OS_WIN32 */
43 #ifndef S_ISLNK
44 #define S_ISLNK(x) 0
45 #endif
47 #ifndef O_BINARY
48 #define O_BINARY 0
49 #endif
51 #include "gfileutils.h"
53 #include "gstdio.h"
54 #include "glibintl.h"
56 #ifdef HAVE_LINUX_MAGIC_H /* for btrfs check */
57 #include <linux/magic.h>
58 #include <sys/vfs.h>
59 #endif
62 /**
63 * SECTION:fileutils
64 * @title: File Utilities
65 * @short_description: various file-related functions
67 * There is a group of functions which wrap the common POSIX functions
68 * dealing with filenames (g_open(), g_rename(), g_mkdir(), g_stat(),
69 * g_unlink(), g_remove(), g_fopen(), g_freopen()). The point of these
70 * wrappers is to make it possible to handle file names with any Unicode
71 * characters in them on Windows without having to use ifdefs and the
72 * wide character API in the application code.
74 * The pathname argument should be in the GLib file name encoding.
75 * On POSIX this is the actual on-disk encoding which might correspond
76 * to the locale settings of the process (or the
77 * <envar>G_FILENAME_ENCODING</envar> environment variable), or not.
79 * On Windows the GLib file name encoding is UTF-8. Note that the
80 * Microsoft C library does not use UTF-8, but has separate APIs for
81 * current system code page and wide characters (UTF-16). The GLib
82 * wrappers call the wide character API if present (on modern Windows
83 * systems), otherwise convert to/from the system code page.
85 * Another group of functions allows to open and read directories
86 * in the GLib file name encoding. These are g_dir_open(),
87 * g_dir_read_name(), g_dir_rewind(), g_dir_close().
90 /**
91 * GFileError:
92 * @G_FILE_ERROR_EXIST: Operation not permitted; only the owner of
93 * the file (or other resource) or processes with special privileges
94 * can perform the operation.
95 * @G_FILE_ERROR_ISDIR: File is a directory; you cannot open a directory
96 * for writing, or create or remove hard links to it.
97 * @G_FILE_ERROR_ACCES: Permission denied; the file permissions do not
98 * allow the attempted operation.
99 * @G_FILE_ERROR_NAMETOOLONG: Filename too long.
100 * @G_FILE_ERROR_NOENT: No such file or directory. This is a "file
101 * doesn't exist" error for ordinary files that are referenced in
102 * contexts where they are expected to already exist.
103 * @G_FILE_ERROR_NOTDIR: A file that isn't a directory was specified when
104 * a directory is required.
105 * @G_FILE_ERROR_NXIO: No such device or address. The system tried to
106 * use the device represented by a file you specified, and it
107 * couldn't find the device. This can mean that the device file was
108 * installed incorrectly, or that the physical device is missing or
109 * not correctly attached to the computer.
110 * @G_FILE_ERROR_NODEV: The underlying file system of the specified file
111 * does not support memory mapping.
112 * @G_FILE_ERROR_ROFS: The directory containing the new link can't be
113 * modified because it's on a read-only file system.
114 * @G_FILE_ERROR_TXTBSY: Text file busy.
115 * @G_FILE_ERROR_FAULT: You passed in a pointer to bad memory.
116 * (GLib won't reliably return this, don't pass in pointers to bad
117 * memory.)
118 * @G_FILE_ERROR_LOOP: Too many levels of symbolic links were encountered
119 * in looking up a file name. This often indicates a cycle of symbolic
120 * links.
121 * @G_FILE_ERROR_NOSPC: No space left on device; write operation on a
122 * file failed because the disk is full.
123 * @G_FILE_ERROR_NOMEM: No memory available. The system cannot allocate
124 * more virtual memory because its capacity is full.
125 * @G_FILE_ERROR_MFILE: The current process has too many files open and
126 * can't open any more. Duplicate descriptors do count toward this
127 * limit.
128 * @G_FILE_ERROR_NFILE: There are too many distinct file openings in the
129 * entire system.
130 * @G_FILE_ERROR_BADF: Bad file descriptor; for example, I/O on a
131 * descriptor that has been closed or reading from a descriptor open
132 * only for writing (or vice versa).
133 * @G_FILE_ERROR_INVAL: Invalid argument. This is used to indicate
134 * various kinds of problems with passing the wrong argument to a
135 * library function.
136 * @G_FILE_ERROR_PIPE: Broken pipe; there is no process reading from the
137 * other end of a pipe. Every library function that returns this
138 * error code also generates a `SIGPIPE' signal; this signal
139 * terminates the program if not handled or blocked. Thus, your
140 * program will never actually see this code unless it has handled
141 * or blocked `SIGPIPE'.
142 * @G_FILE_ERROR_AGAIN: Resource temporarily unavailable; the call might
143 * work if you try again later.
144 * @G_FILE_ERROR_INTR: Interrupted function call; an asynchronous signal
145 * occurred and prevented completion of the call. When this
146 * happens, you should try the call again.
147 * @G_FILE_ERROR_IO: Input/output error; usually used for physical read
148 * or write errors. i.e. the disk or other physical device hardware
149 * is returning errors.
150 * @G_FILE_ERROR_PERM: Operation not permitted; only the owner of the
151 * file (or other resource) or processes with special privileges can
152 * perform the operation.
153 * @G_FILE_ERROR_NOSYS: Function not implemented; this indicates that
154 * the system is missing some functionality.
155 * @G_FILE_ERROR_FAILED: Does not correspond to a UNIX error code; this
156 * is the standard "failed for unspecified reason" error code present
157 * in all #GError error code enumerations. Returned if no specific
158 * code applies.
160 * Values corresponding to @errno codes returned from file operations
161 * on UNIX. Unlike @errno codes, GFileError values are available on
162 * all systems, even Windows. The exact meaning of each code depends
163 * on what sort of file operation you were performing; the UNIX
164 * documentation gives more details. The following error code descriptions
165 * come from the GNU C Library manual, and are under the copyright
166 * of that manual.
168 * It's not very portable to make detailed assumptions about exactly
169 * which errors will be returned from a given operation. Some errors
170 * don't occur on some systems, etc., sometimes there are subtle
171 * differences in when a system will report a given error, etc.
175 * G_FILE_ERROR:
177 * Error domain for file operations. Errors in this domain will
178 * be from the #GFileError enumeration. See #GError for information
179 * on error domains.
183 * GFileTest:
184 * @G_FILE_TEST_IS_REGULAR: %TRUE if the file is a regular file
185 * (not a directory). Note that this test will also return %TRUE
186 * if the tested file is a symlink to a regular file.
187 * @G_FILE_TEST_IS_SYMLINK: %TRUE if the file is a symlink.
188 * @G_FILE_TEST_IS_DIR: %TRUE if the file is a directory.
189 * @G_FILE_TEST_IS_EXECUTABLE: %TRUE if the file is executable.
190 * @G_FILE_TEST_EXISTS: %TRUE if the file exists. It may or may not
191 * be a regular file.
193 * A test to perform on a file using g_file_test().
197 * g_mkdir_with_parents:
198 * @pathname: a pathname in the GLib file name encoding
199 * @mode: permissions to use for newly created directories
201 * Create a directory if it doesn't already exist. Create intermediate
202 * parent directories as needed, too.
204 * Returns: 0 if the directory already exists, or was successfully
205 * created. Returns -1 if an error occurred, with errno set.
207 * Since: 2.8
210 g_mkdir_with_parents (const gchar *pathname,
211 int mode)
213 gchar *fn, *p;
215 if (pathname == NULL || *pathname == '\0')
217 errno = EINVAL;
218 return -1;
221 fn = g_strdup (pathname);
223 if (g_path_is_absolute (fn))
224 p = (gchar *) g_path_skip_root (fn);
225 else
226 p = fn;
230 while (*p && !G_IS_DIR_SEPARATOR (*p))
231 p++;
233 if (!*p)
234 p = NULL;
235 else
236 *p = '\0';
238 if (!g_file_test (fn, G_FILE_TEST_EXISTS))
240 if (g_mkdir (fn, mode) == -1 && errno != EEXIST)
242 int errno_save = errno;
243 g_free (fn);
244 errno = errno_save;
245 return -1;
248 else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
250 g_free (fn);
251 errno = ENOTDIR;
252 return -1;
254 if (p)
256 *p++ = G_DIR_SEPARATOR;
257 while (*p && G_IS_DIR_SEPARATOR (*p))
258 p++;
261 while (p);
263 g_free (fn);
265 return 0;
269 * g_file_test:
270 * @filename: a filename to test in the 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, <literal>(G_FILE_TEST_EXISTS |
275 * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists;
276 * the check whether it's a directory doesn't matter since the existence
277 * test is %TRUE. With the current set of available tests, there's no point
278 * passing in 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 * |[
294 * /&ast; DON'T DO THIS &ast;/
295 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
297 * fd = g_open (filename, O_WRONLY);
298 * /&ast; write to fd &ast;/
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 <envar>PATHEXT</envar> environment variable.
315 * Return value: 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 <literal>EEXIST</literal> this function returns
470 * #G_FILE_ERROR_EXIST. Unlike <literal>errno</literal> 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 * Return value: #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 break;
488 #endif
490 #ifdef EISDIR
491 case EISDIR:
492 return G_FILE_ERROR_ISDIR;
493 break;
494 #endif
496 #ifdef EACCES
497 case EACCES:
498 return G_FILE_ERROR_ACCES;
499 break;
500 #endif
502 #ifdef ENAMETOOLONG
503 case ENAMETOOLONG:
504 return G_FILE_ERROR_NAMETOOLONG;
505 break;
506 #endif
508 #ifdef ENOENT
509 case ENOENT:
510 return G_FILE_ERROR_NOENT;
511 break;
512 #endif
514 #ifdef ENOTDIR
515 case ENOTDIR:
516 return G_FILE_ERROR_NOTDIR;
517 break;
518 #endif
520 #ifdef ENXIO
521 case ENXIO:
522 return G_FILE_ERROR_NXIO;
523 break;
524 #endif
526 #ifdef ENODEV
527 case ENODEV:
528 return G_FILE_ERROR_NODEV;
529 break;
530 #endif
532 #ifdef EROFS
533 case EROFS:
534 return G_FILE_ERROR_ROFS;
535 break;
536 #endif
538 #ifdef ETXTBSY
539 case ETXTBSY:
540 return G_FILE_ERROR_TXTBSY;
541 break;
542 #endif
544 #ifdef EFAULT
545 case EFAULT:
546 return G_FILE_ERROR_FAULT;
547 break;
548 #endif
550 #ifdef ELOOP
551 case ELOOP:
552 return G_FILE_ERROR_LOOP;
553 break;
554 #endif
556 #ifdef ENOSPC
557 case ENOSPC:
558 return G_FILE_ERROR_NOSPC;
559 break;
560 #endif
562 #ifdef ENOMEM
563 case ENOMEM:
564 return G_FILE_ERROR_NOMEM;
565 break;
566 #endif
568 #ifdef EMFILE
569 case EMFILE:
570 return G_FILE_ERROR_MFILE;
571 break;
572 #endif
574 #ifdef ENFILE
575 case ENFILE:
576 return G_FILE_ERROR_NFILE;
577 break;
578 #endif
580 #ifdef EBADF
581 case EBADF:
582 return G_FILE_ERROR_BADF;
583 break;
584 #endif
586 #ifdef EINVAL
587 case EINVAL:
588 return G_FILE_ERROR_INVAL;
589 break;
590 #endif
592 #ifdef EPIPE
593 case EPIPE:
594 return G_FILE_ERROR_PIPE;
595 break;
596 #endif
598 #ifdef EAGAIN
599 case EAGAIN:
600 return G_FILE_ERROR_AGAIN;
601 break;
602 #endif
604 #ifdef EINTR
605 case EINTR:
606 return G_FILE_ERROR_INTR;
607 break;
608 #endif
610 #ifdef EIO
611 case EIO:
612 return G_FILE_ERROR_IO;
613 break;
614 #endif
616 #ifdef EPERM
617 case EPERM:
618 return G_FILE_ERROR_PERM;
619 break;
620 #endif
622 #ifdef ENOSYS
623 case ENOSYS:
624 return G_FILE_ERROR_NOSYS;
625 break;
626 #endif
628 default:
629 return G_FILE_ERROR_FAILED;
630 break;
634 static gboolean
635 get_contents_stdio (const gchar *display_filename,
636 FILE *f,
637 gchar **contents,
638 gsize *length,
639 GError **error)
641 gchar buf[4096];
642 gsize bytes;
643 gchar *str = NULL;
644 gsize total_bytes = 0;
645 gsize total_allocated = 0;
646 gchar *tmp;
648 g_assert (f != NULL);
650 while (!feof (f))
652 gint save_errno;
654 bytes = fread (buf, 1, sizeof (buf), f);
655 save_errno = errno;
657 while ((total_bytes + bytes + 1) > total_allocated)
659 if (str)
660 total_allocated *= 2;
661 else
662 total_allocated = MIN (bytes + 1, sizeof (buf));
664 tmp = g_try_realloc (str, total_allocated);
666 if (tmp == NULL)
668 g_set_error (error,
669 G_FILE_ERROR,
670 G_FILE_ERROR_NOMEM,
671 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),
672 (gulong) total_allocated,
673 display_filename);
675 goto error;
678 str = tmp;
681 if (ferror (f))
683 g_set_error (error,
684 G_FILE_ERROR,
685 g_file_error_from_errno (save_errno),
686 _("Error reading file '%s': %s"),
687 display_filename,
688 g_strerror (save_errno));
690 goto error;
693 memcpy (str + total_bytes, buf, bytes);
695 if (total_bytes + bytes < total_bytes)
697 g_set_error (error,
698 G_FILE_ERROR,
699 G_FILE_ERROR_FAILED,
700 _("File \"%s\" is too large"),
701 display_filename);
703 goto error;
706 total_bytes += bytes;
709 fclose (f);
711 if (total_allocated == 0)
713 str = g_new (gchar, 1);
714 total_bytes = 0;
717 str[total_bytes] = '\0';
719 if (length)
720 *length = total_bytes;
722 *contents = str;
724 return TRUE;
726 error:
728 g_free (str);
729 fclose (f);
731 return FALSE;
734 #ifndef G_OS_WIN32
736 static gboolean
737 get_contents_regfile (const gchar *display_filename,
738 struct stat *stat_buf,
739 gint fd,
740 gchar **contents,
741 gsize *length,
742 GError **error)
744 gchar *buf;
745 gsize bytes_read;
746 gsize size;
747 gsize alloc_size;
749 size = stat_buf->st_size;
751 alloc_size = size + 1;
752 buf = g_try_malloc (alloc_size);
754 if (buf == NULL)
756 g_set_error (error,
757 G_FILE_ERROR,
758 G_FILE_ERROR_NOMEM,
759 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),
760 (gulong) alloc_size,
761 display_filename);
763 goto error;
766 bytes_read = 0;
767 while (bytes_read < size)
769 gssize rc;
771 rc = read (fd, buf + bytes_read, size - bytes_read);
773 if (rc < 0)
775 if (errno != EINTR)
777 int save_errno = errno;
779 g_free (buf);
780 g_set_error (error,
781 G_FILE_ERROR,
782 g_file_error_from_errno (save_errno),
783 _("Failed to read from file '%s': %s"),
784 display_filename,
785 g_strerror (save_errno));
787 goto error;
790 else if (rc == 0)
791 break;
792 else
793 bytes_read += rc;
796 buf[bytes_read] = '\0';
798 if (length)
799 *length = bytes_read;
801 *contents = buf;
803 close (fd);
805 return TRUE;
807 error:
809 close (fd);
811 return FALSE;
814 static gboolean
815 get_contents_posix (const gchar *filename,
816 gchar **contents,
817 gsize *length,
818 GError **error)
820 struct stat stat_buf;
821 gint fd;
822 gchar *display_filename = g_filename_display_name (filename);
824 /* O_BINARY useful on Cygwin */
825 fd = open (filename, O_RDONLY|O_BINARY);
827 if (fd < 0)
829 int save_errno = errno;
831 g_set_error (error,
832 G_FILE_ERROR,
833 g_file_error_from_errno (save_errno),
834 _("Failed to open file '%s': %s"),
835 display_filename,
836 g_strerror (save_errno));
837 g_free (display_filename);
839 return FALSE;
842 /* I don't think this will ever fail, aside from ENOMEM, but. */
843 if (fstat (fd, &stat_buf) < 0)
845 int save_errno = errno;
847 close (fd);
848 g_set_error (error,
849 G_FILE_ERROR,
850 g_file_error_from_errno (save_errno),
851 _("Failed to get attributes of file '%s': fstat() failed: %s"),
852 display_filename,
853 g_strerror (save_errno));
854 g_free (display_filename);
856 return FALSE;
859 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
861 gboolean retval = get_contents_regfile (display_filename,
862 &stat_buf,
864 contents,
865 length,
866 error);
867 g_free (display_filename);
869 return retval;
871 else
873 FILE *f;
874 gboolean retval;
876 f = fdopen (fd, "r");
878 if (f == NULL)
880 int save_errno = errno;
882 g_set_error (error,
883 G_FILE_ERROR,
884 g_file_error_from_errno (save_errno),
885 _("Failed to open file '%s': fdopen() failed: %s"),
886 display_filename,
887 g_strerror (save_errno));
888 g_free (display_filename);
890 return FALSE;
893 retval = get_contents_stdio (display_filename, f, contents, length, error);
894 g_free (display_filename);
896 return retval;
900 #else /* G_OS_WIN32 */
902 static gboolean
903 get_contents_win32 (const gchar *filename,
904 gchar **contents,
905 gsize *length,
906 GError **error)
908 FILE *f;
909 gboolean retval;
910 gchar *display_filename = g_filename_display_name (filename);
911 int save_errno;
913 f = g_fopen (filename, "rb");
914 save_errno = errno;
916 if (f == NULL)
918 g_set_error (error,
919 G_FILE_ERROR,
920 g_file_error_from_errno (save_errno),
921 _("Failed to open file '%s': %s"),
922 display_filename,
923 g_strerror (save_errno));
924 g_free (display_filename);
926 return FALSE;
929 retval = get_contents_stdio (display_filename, f, contents, length, error);
930 g_free (display_filename);
932 return retval;
935 #endif
938 * g_file_get_contents:
939 * @filename: (type filename): name of a file to read contents from, in the GLib file name encoding
940 * @contents: (out) (array length=length) (element-type guint8): location to store an allocated string, use g_free() to free
941 * the returned string
942 * @length: (allow-none): location to store length in bytes of the contents, or %NULL
943 * @error: return location for a #GError, or %NULL
945 * Reads an entire file into allocated memory, with good error
946 * checking.
948 * If the call was successful, it returns %TRUE and sets @contents to the file
949 * contents and @length to the length of the file contents in bytes. The string
950 * stored in @contents will be nul-terminated, so for text files you can pass
951 * %NULL for the @length argument. If the call was not successful, it returns
952 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
953 * codes are those in the #GFileError enumeration. In the error case,
954 * @contents is set to %NULL and @length is set to zero.
956 * Return value: %TRUE on success, %FALSE if an error occurred
958 gboolean
959 g_file_get_contents (const gchar *filename,
960 gchar **contents,
961 gsize *length,
962 GError **error)
964 g_return_val_if_fail (filename != NULL, FALSE);
965 g_return_val_if_fail (contents != NULL, FALSE);
967 *contents = NULL;
968 if (length)
969 *length = 0;
971 #ifdef G_OS_WIN32
972 return get_contents_win32 (filename, contents, length, error);
973 #else
974 return get_contents_posix (filename, contents, length, error);
975 #endif
978 static gboolean
979 rename_file (const char *old_name,
980 const char *new_name,
981 GError **err)
983 errno = 0;
984 if (g_rename (old_name, new_name) == -1)
986 int save_errno = errno;
987 gchar *display_old_name = g_filename_display_name (old_name);
988 gchar *display_new_name = g_filename_display_name (new_name);
990 g_set_error (err,
991 G_FILE_ERROR,
992 g_file_error_from_errno (save_errno),
993 _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
994 display_old_name,
995 display_new_name,
996 g_strerror (save_errno));
998 g_free (display_old_name);
999 g_free (display_new_name);
1001 return FALSE;
1004 return TRUE;
1007 static gchar *
1008 write_to_temp_file (const gchar *contents,
1009 gssize length,
1010 const gchar *dest_file,
1011 GError **err)
1013 gchar *tmp_name;
1014 gchar *display_name;
1015 gchar *retval;
1016 FILE *file;
1017 gint fd;
1018 int save_errno;
1020 retval = NULL;
1022 tmp_name = g_strdup_printf ("%s.XXXXXX", dest_file);
1024 errno = 0;
1025 fd = g_mkstemp_full (tmp_name, O_RDWR | O_BINARY, 0666);
1026 save_errno = errno;
1028 display_name = g_filename_display_name (tmp_name);
1030 if (fd == -1)
1032 g_set_error (err,
1033 G_FILE_ERROR,
1034 g_file_error_from_errno (save_errno),
1035 _("Failed to create file '%s': %s"),
1036 display_name, g_strerror (save_errno));
1038 goto out;
1041 errno = 0;
1042 file = fdopen (fd, "wb");
1043 if (!file)
1045 save_errno = errno;
1046 g_set_error (err,
1047 G_FILE_ERROR,
1048 g_file_error_from_errno (save_errno),
1049 _("Failed to open file '%s' for writing: fdopen() failed: %s"),
1050 display_name,
1051 g_strerror (save_errno));
1053 close (fd);
1054 g_unlink (tmp_name);
1056 goto out;
1059 if (length > 0)
1061 gsize n_written;
1063 errno = 0;
1065 n_written = fwrite (contents, 1, length, file);
1067 if (n_written < length)
1069 save_errno = errno;
1071 g_set_error (err,
1072 G_FILE_ERROR,
1073 g_file_error_from_errno (save_errno),
1074 _("Failed to write file '%s': fwrite() failed: %s"),
1075 display_name,
1076 g_strerror (save_errno));
1078 fclose (file);
1079 g_unlink (tmp_name);
1081 goto out;
1085 errno = 0;
1086 if (fflush (file) != 0)
1088 save_errno = errno;
1090 g_set_error (err,
1091 G_FILE_ERROR,
1092 g_file_error_from_errno (save_errno),
1093 _("Failed to write file '%s': fflush() failed: %s"),
1094 display_name,
1095 g_strerror (save_errno));
1097 fclose (file);
1098 g_unlink (tmp_name);
1100 goto out;
1103 #ifdef BTRFS_SUPER_MAGIC
1105 struct statfs buf;
1107 /* On Linux, on btrfs, skip the fsync since rename-over-existing is
1108 * guaranteed to be atomic and this is the only case in which we
1109 * would fsync() anyway.
1112 if (fstatfs (fd, &buf) == 0 && buf.f_type == BTRFS_SUPER_MAGIC)
1113 goto no_fsync;
1115 #endif
1117 #ifdef HAVE_FSYNC
1119 struct stat statbuf;
1121 errno = 0;
1122 /* If the final destination exists and is > 0 bytes, we want to sync the
1123 * newly written file to ensure the data is on disk when we rename over
1124 * the destination. Otherwise if we get a system crash we can lose both
1125 * the new and the old file on some filesystems. (I.E. those that don't
1126 * guarantee the data is written to the disk before the metadata.)
1128 if (g_lstat (dest_file, &statbuf) == 0 &&
1129 statbuf.st_size > 0 &&
1130 fsync (fileno (file)) != 0)
1132 save_errno = errno;
1134 g_set_error (err,
1135 G_FILE_ERROR,
1136 g_file_error_from_errno (save_errno),
1137 _("Failed to write file '%s': fsync() failed: %s"),
1138 display_name,
1139 g_strerror (save_errno));
1141 fclose (file);
1142 g_unlink (tmp_name);
1144 goto out;
1147 #endif
1149 #ifdef BTRFS_SUPER_MAGIC
1150 no_fsync:
1151 #endif
1153 errno = 0;
1154 if (fclose (file) == EOF)
1156 save_errno = errno;
1158 g_set_error (err,
1159 G_FILE_ERROR,
1160 g_file_error_from_errno (save_errno),
1161 _("Failed to close file '%s': fclose() failed: %s"),
1162 display_name,
1163 g_strerror (save_errno));
1165 g_unlink (tmp_name);
1167 goto out;
1170 retval = g_strdup (tmp_name);
1172 out:
1173 g_free (tmp_name);
1174 g_free (display_name);
1176 return retval;
1180 * g_file_set_contents:
1181 * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1182 * encoding
1183 * @contents: (array length=length) (element-type guint8): string to write to the file
1184 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1185 * @error: return location for a #GError, or %NULL
1187 * Writes all of @contents to a file named @filename, with good error checking.
1188 * If a file called @filename already exists it will be overwritten.
1190 * This write is atomic in the sense that it is first written to a temporary
1191 * file which is then renamed to the final name. Notes:
1192 * <itemizedlist>
1193 * <listitem>
1194 * On Unix, if @filename already exists hard links to @filename will break.
1195 * Also since the file is recreated, existing permissions, access control
1196 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1197 * the link itself will be replaced, not the linked file.
1198 * </listitem>
1199 * <listitem>
1200 * On Windows renaming a file will not remove an existing file with the
1201 * new name, so on Windows there is a race condition between the existing
1202 * file being removed and the temporary file being renamed.
1203 * </listitem>
1204 * <listitem>
1205 * On Windows there is no way to remove a file that is open to some
1206 * process, or mapped into memory. Thus, this function will fail if
1207 * @filename already exists and is open.
1208 * </listitem>
1209 * </itemizedlist>
1211 * If the call was successful, it returns %TRUE. If the call was not successful,
1212 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1213 * Possible error codes are those in the #GFileError enumeration.
1215 * Note that the name for the temporary file is constructed by appending up
1216 * to 7 characters to @filename.
1218 * Return value: %TRUE on success, %FALSE if an error occurred
1220 * Since: 2.8
1222 gboolean
1223 g_file_set_contents (const gchar *filename,
1224 const gchar *contents,
1225 gssize length,
1226 GError **error)
1228 gchar *tmp_filename;
1229 gboolean retval;
1230 GError *rename_error = NULL;
1232 g_return_val_if_fail (filename != NULL, FALSE);
1233 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1234 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1235 g_return_val_if_fail (length >= -1, FALSE);
1237 if (length == -1)
1238 length = strlen (contents);
1240 tmp_filename = write_to_temp_file (contents, length, filename, error);
1242 if (!tmp_filename)
1244 retval = FALSE;
1245 goto out;
1248 if (!rename_file (tmp_filename, filename, &rename_error))
1250 #ifndef G_OS_WIN32
1252 g_unlink (tmp_filename);
1253 g_propagate_error (error, rename_error);
1254 retval = FALSE;
1255 goto out;
1257 #else /* G_OS_WIN32 */
1259 /* Renaming failed, but on Windows this may just mean
1260 * the file already exists. So if the target file
1261 * exists, try deleting it and do the rename again.
1263 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1265 g_unlink (tmp_filename);
1266 g_propagate_error (error, rename_error);
1267 retval = FALSE;
1268 goto out;
1271 g_error_free (rename_error);
1273 if (g_unlink (filename) == -1)
1275 gchar *display_filename = g_filename_display_name (filename);
1277 int save_errno = errno;
1279 g_set_error (error,
1280 G_FILE_ERROR,
1281 g_file_error_from_errno (save_errno),
1282 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1283 display_filename,
1284 g_strerror (save_errno));
1286 g_free (display_filename);
1287 g_unlink (tmp_filename);
1288 retval = FALSE;
1289 goto out;
1292 if (!rename_file (tmp_filename, filename, error))
1294 g_unlink (tmp_filename);
1295 retval = FALSE;
1296 goto out;
1299 #endif
1302 retval = TRUE;
1304 out:
1305 g_free (tmp_filename);
1306 return retval;
1310 * get_tmp_file based on the mkstemp implementation from the GNU C library.
1311 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1313 typedef gint (*GTmpFileCallback) (const gchar *, gint, gint);
1315 static gint
1316 get_tmp_file (gchar *tmpl,
1317 GTmpFileCallback f,
1318 int flags,
1319 int mode)
1321 char *XXXXXX;
1322 int count, fd;
1323 static const char letters[] =
1324 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1325 static const int NLETTERS = sizeof (letters) - 1;
1326 glong value;
1327 GTimeVal tv;
1328 static int counter = 0;
1330 g_return_val_if_fail (tmpl != NULL, -1);
1332 /* find the last occurrence of "XXXXXX" */
1333 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1335 if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1337 errno = EINVAL;
1338 return -1;
1341 /* Get some more or less random data. */
1342 g_get_current_time (&tv);
1343 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1345 for (count = 0; count < 100; value += 7777, ++count)
1347 glong v = value;
1349 /* Fill in the random bits. */
1350 XXXXXX[0] = letters[v % NLETTERS];
1351 v /= NLETTERS;
1352 XXXXXX[1] = letters[v % NLETTERS];
1353 v /= NLETTERS;
1354 XXXXXX[2] = letters[v % NLETTERS];
1355 v /= NLETTERS;
1356 XXXXXX[3] = letters[v % NLETTERS];
1357 v /= NLETTERS;
1358 XXXXXX[4] = letters[v % NLETTERS];
1359 v /= NLETTERS;
1360 XXXXXX[5] = letters[v % NLETTERS];
1362 fd = f (tmpl, flags, mode);
1364 if (fd >= 0)
1365 return fd;
1366 else if (errno != EEXIST)
1367 /* Any other error will apply also to other names we might
1368 * try, and there are 2^32 or so of them, so give up now.
1370 return -1;
1373 /* We got out of the loop because we ran out of combinations to try. */
1374 errno = EEXIST;
1375 return -1;
1378 /* Some GTmpFileCallback implementations.
1380 * Note: we cannot use open() or g_open() directly because even though
1381 * they appear compatible, they may be vararg functions and calling
1382 * varargs functions through a non-varargs type is undefined.
1384 static gint
1385 wrap_g_mkdir (const gchar *filename,
1386 int flags G_GNUC_UNUSED,
1387 int mode)
1389 /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1390 return g_mkdir (filename, mode);
1393 static gint
1394 wrap_g_open (const gchar *filename,
1395 int flags,
1396 int mode)
1398 return g_open (filename, flags, mode);
1402 * g_mkdtemp_full:
1403 * @tmpl: (type filename): template directory name
1404 * @mode: permissions to create the temporary directory with
1406 * Creates a temporary directory. See the mkdtemp() documentation
1407 * on most UNIX-like systems.
1409 * The parameter is a string that should follow the rules for
1410 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1411 * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1412 * sequence does not have to occur at the very end of the template
1413 * and you can pass a @mode. The X string will be modified to form
1414 * the name of a directory that didn't exist. The string should be
1415 * in the GLib file name encoding. Most importantly, on Windows it
1416 * should be in UTF-8.
1418 * Return value: A pointer to @tmpl, which has been modified
1419 * to hold the directory name. In case of errors, %NULL is
1420 * returned, and %errno will be set.
1422 * Since: 2.30
1424 gchar *
1425 g_mkdtemp_full (gchar *tmpl,
1426 gint mode)
1428 if (get_tmp_file (tmpl, wrap_g_mkdir, 0, mode) == -1)
1429 return NULL;
1430 else
1431 return tmpl;
1435 * g_mkdtemp:
1436 * @tmpl: (type filename): template directory name
1438 * Creates a temporary directory. See the mkdtemp() documentation
1439 * on most UNIX-like systems.
1441 * The parameter is a string that should follow the rules for
1442 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1443 * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1444 * sequence does not have to occur at the very end of the template
1445 * and you can pass a @mode and additional @flags. The X string will
1446 * be modified to form the name of a directory that didn't exist.
1447 * The string should be in the GLib file name encoding. Most importantly,
1448 * on Windows it should be in UTF-8.
1450 * Return value: A pointer to @tmpl, which has been modified
1451 * to hold the directory name. In case of errors, %NULL is
1452 * returned and %errno will be set.
1454 * Since: 2.30
1456 gchar *
1457 g_mkdtemp (gchar *tmpl)
1459 return g_mkdtemp_full (tmpl, 0700);
1463 * g_mkstemp_full:
1464 * @tmpl: (type filename): template filename
1465 * @flags: flags to pass to an open() call in addition to O_EXCL
1466 * and O_CREAT, which are passed automatically
1467 * @mode: permissions to create the temporary file with
1469 * Opens a temporary file. See the mkstemp() documentation
1470 * on most UNIX-like systems.
1472 * The parameter is a string that should follow the rules for
1473 * mkstemp() templates, i.e. contain the string "XXXXXX".
1474 * g_mkstemp_full() is slightly more flexible than mkstemp()
1475 * in that the sequence does not have to occur at the very end of the
1476 * template and you can pass a @mode and additional @flags. The X
1477 * string will be modified to form the name of a file that didn't exist.
1478 * The string should be in the GLib file name encoding. Most importantly,
1479 * on Windows it should be in UTF-8.
1481 * Return value: A file handle (as from open()) to the file
1482 * opened for reading and writing. The file handle should be
1483 * closed with close(). In case of errors, -1 is returned
1484 * and %errno will be set.
1486 * Since: 2.22
1488 gint
1489 g_mkstemp_full (gchar *tmpl,
1490 gint flags,
1491 gint mode)
1493 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1494 return get_tmp_file (tmpl, wrap_g_open,
1495 flags | O_CREAT | O_EXCL, mode);
1499 * g_mkstemp:
1500 * @tmpl: (type filename): template filename
1502 * Opens a temporary file. See the mkstemp() documentation
1503 * on most UNIX-like systems.
1505 * The parameter is a string that should follow the rules for
1506 * mkstemp() templates, i.e. contain the string "XXXXXX".
1507 * g_mkstemp() is slightly more flexible than mkstemp() in that the
1508 * sequence does not have to occur at the very end of the template.
1509 * The X string will be modified to form the name of a file that
1510 * didn't exist. The string should be in the GLib file name encoding.
1511 * Most importantly, on Windows it should be in UTF-8.
1513 * Return value: A file handle (as from open()) to the file
1514 * opened for reading and writing. The file is opened in binary
1515 * mode on platforms where there is a difference. The file handle
1516 * should be closed with close(). In case of errors, -1 is
1517 * returned and %errno will be set.
1519 gint
1520 g_mkstemp (gchar *tmpl)
1522 return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1525 static gint
1526 g_get_tmp_name (const gchar *tmpl,
1527 gchar **name_used,
1528 GTmpFileCallback f,
1529 gint flags,
1530 gint mode,
1531 GError **error)
1533 int retval;
1534 const char *tmpdir;
1535 const char *sep;
1536 char *fulltemplate;
1537 const char *slash;
1539 if (tmpl == NULL)
1540 tmpl = ".XXXXXX";
1542 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1543 #ifdef G_OS_WIN32
1544 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1545 #endif
1548 gchar *display_tmpl = g_filename_display_name (tmpl);
1549 char c[2];
1550 c[0] = *slash;
1551 c[1] = '\0';
1553 g_set_error (error,
1554 G_FILE_ERROR,
1555 G_FILE_ERROR_FAILED,
1556 _("Template '%s' invalid, should not contain a '%s'"),
1557 display_tmpl, c);
1558 g_free (display_tmpl);
1560 return -1;
1563 if (strstr (tmpl, "XXXXXX") == NULL)
1565 gchar *display_tmpl = g_filename_display_name (tmpl);
1566 g_set_error (error,
1567 G_FILE_ERROR,
1568 G_FILE_ERROR_FAILED,
1569 _("Template '%s' doesn't contain XXXXXX"),
1570 display_tmpl);
1571 g_free (display_tmpl);
1572 return -1;
1575 tmpdir = g_get_tmp_dir ();
1577 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1578 sep = "";
1579 else
1580 sep = G_DIR_SEPARATOR_S;
1582 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1584 retval = get_tmp_file (fulltemplate, f, flags, mode);
1585 if (retval == -1)
1587 int save_errno = errno;
1588 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1590 g_set_error (error,
1591 G_FILE_ERROR,
1592 g_file_error_from_errno (save_errno),
1593 _("Failed to create file '%s': %s"),
1594 display_fulltemplate, g_strerror (save_errno));
1595 g_free (display_fulltemplate);
1596 g_free (fulltemplate);
1597 return -1;
1600 *name_used = fulltemplate;
1602 return retval;
1606 * g_file_open_tmp:
1607 * @tmpl: (type filename) (allow-none): Template for file name, as in
1608 * g_mkstemp(), basename only, or %NULL for a default template
1609 * @name_used: (out) (type filename): location to store actual name used,
1610 * or %NULL
1611 * @error: return location for a #GError
1613 * Opens a file for writing in the preferred directory for temporary
1614 * files (as returned by g_get_tmp_dir()).
1616 * @tmpl should be a string in the GLib file name encoding containing
1617 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1618 * However, unlike these functions, the template should only be a
1619 * basename, no directory components are allowed. If template is
1620 * %NULL, a default template is used.
1622 * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
1623 * modified, and might thus be a read-only literal string.
1625 * Upon success, and if @name_used is non-%NULL, the actual name used
1626 * is returned in @name_used. This string should be freed with g_free()
1627 * when not needed any longer. The returned name is in the GLib file
1628 * name encoding.
1630 * Return value: A file handle (as from open()) to the file opened for
1631 * reading and writing. The file is opened in binary mode on platforms
1632 * where there is a difference. The file handle should be closed with
1633 * close(). In case of errors, -1 is returned and @error will be set.
1635 gint
1636 g_file_open_tmp (const gchar *tmpl,
1637 gchar **name_used,
1638 GError **error)
1640 gchar *fulltemplate;
1641 gint result;
1643 result = g_get_tmp_name (tmpl, &fulltemplate,
1644 wrap_g_open,
1645 O_CREAT | O_EXCL | O_RDWR | O_BINARY,
1646 0600,
1647 error);
1648 if (result != -1)
1650 if (name_used)
1651 *name_used = fulltemplate;
1652 else
1653 g_free (fulltemplate);
1656 return result;
1660 * g_dir_make_tmp:
1661 * @tmpl: (type filename) (allow-none): Template for directory name,
1662 * as in g_mkdtemp(), basename only, or %NULL for a default template
1663 * @error: return location for a #GError
1665 * Creates a subdirectory in the preferred directory for temporary
1666 * files (as returned by g_get_tmp_dir()).
1668 * @tmpl should be a string in the GLib file name encoding containing
1669 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1670 * However, unlike these functions, the template should only be a
1671 * basename, no directory components are allowed. If template is
1672 * %NULL, a default template is used.
1674 * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
1675 * modified, and might thus be a read-only literal string.
1677 * Return value: (type filename): The actual name used. This string
1678 * should be freed with g_free() when not needed any longer and is
1679 * is in the GLib file name encoding. In case of errors, %NULL is
1680 * returned and @error will be set.
1682 * Since: 2.30
1684 gchar *
1685 g_dir_make_tmp (const gchar *tmpl,
1686 GError **error)
1688 gchar *fulltemplate;
1690 if (g_get_tmp_name (tmpl, &fulltemplate, wrap_g_mkdir, 0, 0700, error) == -1)
1691 return NULL;
1692 else
1693 return fulltemplate;
1696 static gchar *
1697 g_build_path_va (const gchar *separator,
1698 const gchar *first_element,
1699 va_list *args,
1700 gchar **str_array)
1702 GString *result;
1703 gint separator_len = strlen (separator);
1704 gboolean is_first = TRUE;
1705 gboolean have_leading = FALSE;
1706 const gchar *single_element = NULL;
1707 const gchar *next_element;
1708 const gchar *last_trailing = NULL;
1709 gint i = 0;
1711 result = g_string_new (NULL);
1713 if (str_array)
1714 next_element = str_array[i++];
1715 else
1716 next_element = first_element;
1718 while (TRUE)
1720 const gchar *element;
1721 const gchar *start;
1722 const gchar *end;
1724 if (next_element)
1726 element = next_element;
1727 if (str_array)
1728 next_element = str_array[i++];
1729 else
1730 next_element = va_arg (*args, gchar *);
1732 else
1733 break;
1735 /* Ignore empty elements */
1736 if (!*element)
1737 continue;
1739 start = element;
1741 if (separator_len)
1743 while (strncmp (start, separator, separator_len) == 0)
1744 start += separator_len;
1747 end = start + strlen (start);
1749 if (separator_len)
1751 while (end >= start + separator_len &&
1752 strncmp (end - separator_len, separator, separator_len) == 0)
1753 end -= separator_len;
1755 last_trailing = end;
1756 while (last_trailing >= element + separator_len &&
1757 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1758 last_trailing -= separator_len;
1760 if (!have_leading)
1762 /* If the leading and trailing separator strings are in the
1763 * same element and overlap, the result is exactly that element
1765 if (last_trailing <= start)
1766 single_element = element;
1768 g_string_append_len (result, element, start - element);
1769 have_leading = TRUE;
1771 else
1772 single_element = NULL;
1775 if (end == start)
1776 continue;
1778 if (!is_first)
1779 g_string_append (result, separator);
1781 g_string_append_len (result, start, end - start);
1782 is_first = FALSE;
1785 if (single_element)
1787 g_string_free (result, TRUE);
1788 return g_strdup (single_element);
1790 else
1792 if (last_trailing)
1793 g_string_append (result, last_trailing);
1795 return g_string_free (result, FALSE);
1800 * g_build_pathv:
1801 * @separator: a string used to separator the elements of the path.
1802 * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
1804 * Behaves exactly like g_build_path(), but takes the path elements
1805 * as a string array, instead of varargs. This function is mainly
1806 * meant for language bindings.
1808 * Return value: a newly-allocated string that must be freed with g_free().
1810 * Since: 2.8
1812 gchar *
1813 g_build_pathv (const gchar *separator,
1814 gchar **args)
1816 if (!args)
1817 return NULL;
1819 return g_build_path_va (separator, NULL, NULL, args);
1824 * g_build_path:
1825 * @separator: a string used to separator the elements of the path.
1826 * @first_element: the first element in the path
1827 * @...: remaining elements in path, terminated by %NULL
1829 * Creates a path from a series of elements using @separator as the
1830 * separator between elements. At the boundary between two elements,
1831 * any trailing occurrences of separator in the first element, or
1832 * leading occurrences of separator in the second element are removed
1833 * and exactly one copy of the separator is inserted.
1835 * Empty elements are ignored.
1837 * The number of leading copies of the separator on the result is
1838 * the same as the number of leading copies of the separator on
1839 * the first non-empty element.
1841 * The number of trailing copies of the separator on the result is
1842 * the same as the number of trailing copies of the separator on
1843 * the last non-empty element. (Determination of the number of
1844 * trailing copies is done without stripping leading copies, so
1845 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1846 * has 1 trailing copy.)
1848 * However, if there is only a single non-empty element, and there
1849 * are no characters in that element not part of the leading or
1850 * trailing separators, then the result is exactly the original value
1851 * of that element.
1853 * Other than for determination of the number of leading and trailing
1854 * copies of the separator, elements consisting only of copies
1855 * of the separator are ignored.
1857 * Return value: a newly-allocated string that must be freed with g_free().
1859 gchar *
1860 g_build_path (const gchar *separator,
1861 const gchar *first_element,
1862 ...)
1864 gchar *str;
1865 va_list args;
1867 g_return_val_if_fail (separator != NULL, NULL);
1869 va_start (args, first_element);
1870 str = g_build_path_va (separator, first_element, &args, NULL);
1871 va_end (args);
1873 return str;
1876 #ifdef G_OS_WIN32
1878 static gchar *
1879 g_build_pathname_va (const gchar *first_element,
1880 va_list *args,
1881 gchar **str_array)
1883 /* Code copied from g_build_pathv(), and modified to use two
1884 * alternative single-character separators.
1886 GString *result;
1887 gboolean is_first = TRUE;
1888 gboolean have_leading = FALSE;
1889 const gchar *single_element = NULL;
1890 const gchar *next_element;
1891 const gchar *last_trailing = NULL;
1892 gchar current_separator = '\\';
1893 gint i = 0;
1895 result = g_string_new (NULL);
1897 if (str_array)
1898 next_element = str_array[i++];
1899 else
1900 next_element = first_element;
1902 while (TRUE)
1904 const gchar *element;
1905 const gchar *start;
1906 const gchar *end;
1908 if (next_element)
1910 element = next_element;
1911 if (str_array)
1912 next_element = str_array[i++];
1913 else
1914 next_element = va_arg (*args, gchar *);
1916 else
1917 break;
1919 /* Ignore empty elements */
1920 if (!*element)
1921 continue;
1923 start = element;
1925 if (TRUE)
1927 while (start &&
1928 (*start == '\\' || *start == '/'))
1930 current_separator = *start;
1931 start++;
1935 end = start + strlen (start);
1937 if (TRUE)
1939 while (end >= start + 1 &&
1940 (end[-1] == '\\' || end[-1] == '/'))
1942 current_separator = end[-1];
1943 end--;
1946 last_trailing = end;
1947 while (last_trailing >= element + 1 &&
1948 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1949 last_trailing--;
1951 if (!have_leading)
1953 /* If the leading and trailing separator strings are in the
1954 * same element and overlap, the result is exactly that element
1956 if (last_trailing <= start)
1957 single_element = element;
1959 g_string_append_len (result, element, start - element);
1960 have_leading = TRUE;
1962 else
1963 single_element = NULL;
1966 if (end == start)
1967 continue;
1969 if (!is_first)
1970 g_string_append_len (result, &current_separator, 1);
1972 g_string_append_len (result, start, end - start);
1973 is_first = FALSE;
1976 if (single_element)
1978 g_string_free (result, TRUE);
1979 return g_strdup (single_element);
1981 else
1983 if (last_trailing)
1984 g_string_append (result, last_trailing);
1986 return g_string_free (result, FALSE);
1990 #endif
1993 * g_build_filenamev:
1994 * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
1996 * Behaves exactly like g_build_filename(), but takes the path elements
1997 * as a string array, instead of varargs. This function is mainly
1998 * meant for language bindings.
2000 * Return value: a newly-allocated string that must be freed with g_free().
2002 * Since: 2.8
2004 gchar *
2005 g_build_filenamev (gchar **args)
2007 gchar *str;
2009 #ifndef G_OS_WIN32
2010 str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
2011 #else
2012 str = g_build_pathname_va (NULL, NULL, args);
2013 #endif
2015 return str;
2019 * g_build_filename:
2020 * @first_element: the first element in the path
2021 * @...: remaining elements in path, terminated by %NULL
2023 * Creates a filename from a series of elements using the correct
2024 * separator for filenames.
2026 * On Unix, this function behaves identically to <literal>g_build_path
2027 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
2029 * On Windows, it takes into account that either the backslash
2030 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
2031 * as separator in filenames, but otherwise behaves as on Unix. When
2032 * file pathname separators need to be inserted, the one that last
2033 * previously occurred in the parameters (reading from left to right)
2034 * is used.
2036 * No attempt is made to force the resulting filename to be an absolute
2037 * path. If the first element is a relative path, the result will
2038 * be a relative path.
2040 * Return value: a newly-allocated string that must be freed with g_free().
2042 gchar *
2043 g_build_filename (const gchar *first_element,
2044 ...)
2046 gchar *str;
2047 va_list args;
2049 va_start (args, first_element);
2050 #ifndef G_OS_WIN32
2051 str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
2052 #else
2053 str = g_build_pathname_va (first_element, &args, NULL);
2054 #endif
2055 va_end (args);
2057 return str;
2061 * g_file_read_link:
2062 * @filename: the symbolic link
2063 * @error: return location for a #GError
2065 * Reads the contents of the symbolic link @filename like the POSIX
2066 * readlink() function. The returned string is in the encoding used
2067 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
2069 * Returns: A newly-allocated string with the contents of the symbolic link,
2070 * or %NULL if an error occurred.
2072 * Since: 2.4
2074 gchar *
2075 g_file_read_link (const gchar *filename,
2076 GError **error)
2078 #ifdef HAVE_READLINK
2079 gchar *buffer;
2080 guint size;
2081 gint read_size;
2083 size = 256;
2084 buffer = g_malloc (size);
2086 while (TRUE)
2088 read_size = readlink (filename, buffer, size);
2089 if (read_size < 0) {
2090 int save_errno = errno;
2091 gchar *display_filename = g_filename_display_name (filename);
2093 g_free (buffer);
2094 g_set_error (error,
2095 G_FILE_ERROR,
2096 g_file_error_from_errno (save_errno),
2097 _("Failed to read the symbolic link '%s': %s"),
2098 display_filename,
2099 g_strerror (save_errno));
2100 g_free (display_filename);
2102 return NULL;
2105 if (read_size < size)
2107 buffer[read_size] = 0;
2108 return buffer;
2111 size *= 2;
2112 buffer = g_realloc (buffer, size);
2114 #else
2115 g_set_error_literal (error,
2116 G_FILE_ERROR,
2117 G_FILE_ERROR_INVAL,
2118 _("Symbolic links not supported"));
2120 return NULL;
2121 #endif
2125 * g_path_is_absolute:
2126 * @file_name: a file name
2128 * Returns %TRUE if the given @file_name is an absolute file name.
2129 * Note that this is a somewhat vague concept on Windows.
2131 * On POSIX systems, an absolute file name is well-defined. It always
2132 * starts from the single root directory. For example "/usr/local".
2134 * On Windows, the concepts of current drive and drive-specific
2135 * current directory introduce vagueness. This function interprets as
2136 * an absolute file name one that either begins with a directory
2137 * separator such as "\Users\tml" or begins with the root on a drive,
2138 * for example "C:\Windows". The first case also includes UNC paths
2139 * such as "\\myserver\docs\foo". In all cases, either slashes or
2140 * backslashes are accepted.
2142 * Note that a file name relative to the current drive root does not
2143 * truly specify a file uniquely over time and across processes, as
2144 * the current drive is a per-process value and can be changed.
2146 * File names relative the current directory on some specific drive,
2147 * such as "D:foo/bar", are not interpreted as absolute by this
2148 * function, but they obviously are not relative to the normal current
2149 * directory as returned by getcwd() or g_get_current_dir()
2150 * either. Such paths should be avoided, or need to be handled using
2151 * Windows-specific code.
2153 * Returns: %TRUE if @file_name is absolute
2155 gboolean
2156 g_path_is_absolute (const gchar *file_name)
2158 g_return_val_if_fail (file_name != NULL, FALSE);
2160 if (G_IS_DIR_SEPARATOR (file_name[0]))
2161 return TRUE;
2163 #ifdef G_OS_WIN32
2164 /* Recognize drive letter on native Windows */
2165 if (g_ascii_isalpha (file_name[0]) &&
2166 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
2167 return TRUE;
2168 #endif
2170 return FALSE;
2174 * g_path_skip_root:
2175 * @file_name: a file name
2177 * Returns a pointer into @file_name after the root component,
2178 * i.e. after the "/" in UNIX or "C:\" under Windows. If @file_name
2179 * is not an absolute path it returns %NULL.
2181 * Returns: a pointer into @file_name after the root component
2183 const gchar *
2184 g_path_skip_root (const gchar *file_name)
2186 g_return_val_if_fail (file_name != NULL, NULL);
2188 #ifdef G_PLATFORM_WIN32
2189 /* Skip \\server\share or //server/share */
2190 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2191 G_IS_DIR_SEPARATOR (file_name[1]) &&
2192 file_name[2] &&
2193 !G_IS_DIR_SEPARATOR (file_name[2]))
2195 gchar *p;
2196 p = strchr (file_name + 2, G_DIR_SEPARATOR);
2198 #ifdef G_OS_WIN32
2200 gchar *q;
2202 q = strchr (file_name + 2, '/');
2203 if (p == NULL || (q != NULL && q < p))
2204 p = q;
2206 #endif
2208 if (p && p > file_name + 2 && p[1])
2210 file_name = p + 1;
2212 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
2213 file_name++;
2215 /* Possibly skip a backslash after the share name */
2216 if (G_IS_DIR_SEPARATOR (file_name[0]))
2217 file_name++;
2219 return (gchar *)file_name;
2222 #endif
2224 /* Skip initial slashes */
2225 if (G_IS_DIR_SEPARATOR (file_name[0]))
2227 while (G_IS_DIR_SEPARATOR (file_name[0]))
2228 file_name++;
2229 return (gchar *)file_name;
2232 #ifdef G_OS_WIN32
2233 /* Skip X:\ */
2234 if (g_ascii_isalpha (file_name[0]) &&
2235 file_name[1] == ':' &&
2236 G_IS_DIR_SEPARATOR (file_name[2]))
2237 return (gchar *)file_name + 3;
2238 #endif
2240 return NULL;
2244 * g_basename:
2245 * @file_name: the name of the file
2247 * Gets the name of the file without any leading directory
2248 * components. It returns a pointer into the given file name
2249 * string.
2251 * Return value: the name of the file without any leading
2252 * directory components
2254 * Deprecated:2.2: Use g_path_get_basename() instead, but notice
2255 * that g_path_get_basename() allocates new memory for the
2256 * returned string, unlike this function which returns a pointer
2257 * into the argument.
2259 const gchar *
2260 g_basename (const gchar *file_name)
2262 gchar *base;
2264 g_return_val_if_fail (file_name != NULL, NULL);
2266 base = strrchr (file_name, G_DIR_SEPARATOR);
2268 #ifdef G_OS_WIN32
2270 gchar *q;
2271 q = strrchr (file_name, '/');
2272 if (base == NULL || (q != NULL && q > base))
2273 base = q;
2275 #endif
2277 if (base)
2278 return base + 1;
2280 #ifdef G_OS_WIN32
2281 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2282 return (gchar*) file_name + 2;
2283 #endif
2285 return (gchar*) file_name;
2289 * g_path_get_basename:
2290 * @file_name: the name of the file
2292 * Gets the last component of the filename.
2294 * If @file_name ends with a directory separator it gets the component
2295 * before the last slash. If @file_name consists only of directory
2296 * separators (and on Windows, possibly a drive letter), a single
2297 * separator is returned. If @file_name is empty, it gets ".".
2299 * Return value: a newly allocated string containing the last
2300 * component of the filename
2302 gchar *
2303 g_path_get_basename (const gchar *file_name)
2305 gssize base;
2306 gssize last_nonslash;
2307 gsize len;
2308 gchar *retval;
2310 g_return_val_if_fail (file_name != NULL, NULL);
2312 if (file_name[0] == '\0')
2313 return g_strdup (".");
2315 last_nonslash = strlen (file_name) - 1;
2317 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
2318 last_nonslash--;
2320 if (last_nonslash == -1)
2321 /* string only containing slashes */
2322 return g_strdup (G_DIR_SEPARATOR_S);
2324 #ifdef G_OS_WIN32
2325 if (last_nonslash == 1 &&
2326 g_ascii_isalpha (file_name[0]) &&
2327 file_name[1] == ':')
2328 /* string only containing slashes and a drive */
2329 return g_strdup (G_DIR_SEPARATOR_S);
2330 #endif
2331 base = last_nonslash;
2333 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
2334 base--;
2336 #ifdef G_OS_WIN32
2337 if (base == -1 &&
2338 g_ascii_isalpha (file_name[0]) &&
2339 file_name[1] == ':')
2340 base = 1;
2341 #endif /* G_OS_WIN32 */
2343 len = last_nonslash - base;
2344 retval = g_malloc (len + 1);
2345 memcpy (retval, file_name + base + 1, len);
2346 retval [len] = '\0';
2348 return retval;
2352 * g_dirname:
2353 * @file_name: the name of the file
2355 * Gets the directory components of a file name.
2357 * If the file name has no directory components "." is returned.
2358 * The returned string should be freed when no longer needed.
2360 * Returns: the directory components of the file
2362 * Deprecated: use g_path_get_dirname() instead
2366 * g_path_get_dirname:
2367 * @file_name: the name of the file
2369 * Gets the directory components of a file name.
2371 * If the file name has no directory components "." is returned.
2372 * The returned string should be freed when no longer needed.
2374 * Returns: the directory components of the file
2376 gchar *
2377 g_path_get_dirname (const gchar *file_name)
2379 gchar *base;
2380 gsize len;
2382 g_return_val_if_fail (file_name != NULL, NULL);
2384 base = strrchr (file_name, G_DIR_SEPARATOR);
2386 #ifdef G_OS_WIN32
2388 gchar *q;
2389 q = strrchr (file_name, '/');
2390 if (base == NULL || (q != NULL && q > base))
2391 base = q;
2393 #endif
2395 if (!base)
2397 #ifdef G_OS_WIN32
2398 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2400 gchar drive_colon_dot[4];
2402 drive_colon_dot[0] = file_name[0];
2403 drive_colon_dot[1] = ':';
2404 drive_colon_dot[2] = '.';
2405 drive_colon_dot[3] = '\0';
2407 return g_strdup (drive_colon_dot);
2409 #endif
2410 return g_strdup (".");
2413 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
2414 base--;
2416 #ifdef G_OS_WIN32
2417 /* base points to the char before the last slash.
2419 * In case file_name is the root of a drive (X:\) or a child of the
2420 * root of a drive (X:\foo), include the slash.
2422 * In case file_name is the root share of an UNC path
2423 * (\\server\share), add a slash, returning \\server\share\ .
2425 * In case file_name is a direct child of a share in an UNC path
2426 * (\\server\share\foo), include the slash after the share name,
2427 * returning \\server\share\ .
2429 if (base == file_name + 1 &&
2430 g_ascii_isalpha (file_name[0]) &&
2431 file_name[1] == ':')
2432 base++;
2433 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2434 G_IS_DIR_SEPARATOR (file_name[1]) &&
2435 file_name[2] &&
2436 !G_IS_DIR_SEPARATOR (file_name[2]) &&
2437 base >= file_name + 2)
2439 const gchar *p = file_name + 2;
2440 while (*p && !G_IS_DIR_SEPARATOR (*p))
2441 p++;
2442 if (p == base + 1)
2444 len = (guint) strlen (file_name) + 1;
2445 base = g_new (gchar, len + 1);
2446 strcpy (base, file_name);
2447 base[len-1] = G_DIR_SEPARATOR;
2448 base[len] = 0;
2449 return base;
2451 if (G_IS_DIR_SEPARATOR (*p))
2453 p++;
2454 while (*p && !G_IS_DIR_SEPARATOR (*p))
2455 p++;
2456 if (p == base + 1)
2457 base++;
2460 #endif
2462 len = (guint) 1 + base - file_name;
2463 base = g_new (gchar, len + 1);
2464 g_memmove (base, file_name, len);
2465 base[len] = 0;
2467 return base;
2470 #if defined(MAXPATHLEN)
2471 #define G_PATH_LENGTH MAXPATHLEN
2472 #elif defined(PATH_MAX)
2473 #define G_PATH_LENGTH PATH_MAX
2474 #elif defined(_PC_PATH_MAX)
2475 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
2476 #else
2477 #define G_PATH_LENGTH 2048
2478 #endif
2481 * g_get_current_dir:
2483 * Gets the current directory.
2485 * The returned string should be freed when no longer needed.
2486 * The encoding of the returned string is system defined.
2487 * On Windows, it is always UTF-8.
2489 * Returns: the current directory
2491 gchar *
2492 g_get_current_dir (void)
2494 #ifdef G_OS_WIN32
2496 gchar *dir = NULL;
2497 wchar_t dummy[2], *wdir;
2498 int len;
2500 len = GetCurrentDirectoryW (2, dummy);
2501 wdir = g_new (wchar_t, len);
2503 if (GetCurrentDirectoryW (len, wdir) == len - 1)
2504 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
2506 g_free (wdir);
2508 if (dir == NULL)
2509 dir = g_strdup ("\\");
2511 return dir;
2513 #else
2515 gchar *buffer = NULL;
2516 gchar *dir = NULL;
2517 static gulong max_len = 0;
2519 if (max_len == 0)
2520 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
2522 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
2523 * and, if that wasn't bad enough, hangs in doing so.
2525 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
2526 buffer = g_new (gchar, max_len + 1);
2527 *buffer = 0;
2528 dir = getwd (buffer);
2529 #else
2530 while (max_len < G_MAXULONG / 2)
2532 g_free (buffer);
2533 buffer = g_new (gchar, max_len + 1);
2534 *buffer = 0;
2535 dir = getcwd (buffer, max_len);
2537 if (dir || errno != ERANGE)
2538 break;
2540 max_len *= 2;
2542 #endif /* !sun || !HAVE_GETCWD */
2544 if (!dir || !*buffer)
2546 /* hm, should we g_error() out here?
2547 * this can happen if e.g. "./" has mode \0000
2549 buffer[0] = G_DIR_SEPARATOR;
2550 buffer[1] = 0;
2553 dir = g_strdup (buffer);
2554 g_free (buffer);
2556 return dir;
2558 #endif /* !G_OS_WIN32 */
2562 /* NOTE : Keep this part last to ensure nothing in this file uses thn
2563 * below binary compatibility versions.
2565 #if defined (G_OS_WIN32) && !defined (_WIN64)
2567 /* Binary compatibility versions. Will be called by code compiled
2568 * against quite old (pre-2.8, I think) headers only, not from more
2569 * recently compiled code.
2572 #undef g_file_test
2574 gboolean
2575 g_file_test (const gchar *filename,
2576 GFileTest test)
2578 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
2579 gboolean retval;
2581 if (utf8_filename == NULL)
2582 return FALSE;
2584 retval = g_file_test_utf8 (utf8_filename, test);
2586 g_free (utf8_filename);
2588 return retval;
2591 #undef g_file_get_contents
2593 gboolean
2594 g_file_get_contents (const gchar *filename,
2595 gchar **contents,
2596 gsize *length,
2597 GError **error)
2599 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
2600 gboolean retval;
2602 if (utf8_filename == NULL)
2603 return FALSE;
2605 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
2607 g_free (utf8_filename);
2609 return retval;
2612 #undef g_mkstemp
2614 static gint
2615 wrap_libc_open (const gchar *filename,
2616 int flags,
2617 int mode)
2619 return open (filename, flags, mode);
2622 gint
2623 g_mkstemp (gchar *tmpl)
2625 /* This is the backward compatibility system codepage version,
2626 * thus use normal open().
2628 return get_tmp_file (tmpl, wrap_libc_open,
2629 O_RDWR | O_CREAT | O_EXCL, 0600);
2632 #undef g_file_open_tmp
2634 gint
2635 g_file_open_tmp (const gchar *tmpl,
2636 gchar **name_used,
2637 GError **error)
2639 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
2640 gchar *utf8_name_used;
2641 gint retval;
2643 if (utf8_tmpl == NULL)
2644 return -1;
2646 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
2648 if (retval == -1)
2649 return -1;
2651 if (name_used)
2652 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
2654 g_free (utf8_name_used);
2656 return retval;
2659 #undef g_get_current_dir
2661 gchar *
2662 g_get_current_dir (void)
2664 gchar *utf8_dir = g_get_current_dir_utf8 ();
2665 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
2666 g_free (utf8_dir);
2667 return dir;
2670 #endif