1 /* gfileutils.c - File utility functions
3 * Copyright 2000 Red Hat, Inc.
5 * SPDX-License-Identifier: LGPL-2.1-or-later
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with this library; if not, see <http://www.gnu.org/licenses/>.
22 #include "glibconfig.h"
30 #include <sys/types.h>
41 #endif /* G_OS_WIN32 */
55 #include "gfileutils.h"
58 #include "gstdioprivate.h"
64 * @title: File Utilities
65 * @short_description: various file-related functions
67 * Do not use these APIs unless you are porting a POSIX application to Windows.
68 * A more high-level file access API is provided as GIO — see the documentation
71 * There is a group of functions which wrap the common POSIX functions
72 * dealing with filenames (g_open(), g_rename(), g_mkdir(), g_stat(),
73 * g_unlink(), g_remove(), g_fopen(), g_freopen()). The point of these
74 * wrappers is to make it possible to handle file names with any Unicode
75 * characters in them on Windows without having to use ifdefs and the
76 * wide character API in the application code.
78 * On some Unix systems, these APIs may be defined as identical to their POSIX
79 * counterparts. For this reason, you must check for and include the necessary
80 * header files (such as `fcntl.h`) before using functions like g_creat(). You
81 * must also define the relevant feature test macros.
83 * The pathname argument should be in the GLib file name encoding.
84 * On POSIX this is the actual on-disk encoding which might correspond
85 * to the locale settings of the process (or the `G_FILENAME_ENCODING`
86 * environment variable), or not.
88 * On Windows the GLib file name encoding is UTF-8. Note that the
89 * Microsoft C library does not use UTF-8, but has separate APIs for
90 * current system code page and wide characters (UTF-16). The GLib
91 * wrappers call the wide character API if present (on modern Windows
92 * systems), otherwise convert to/from the system code page.
94 * Another group of functions allows to open and read directories
95 * in the GLib file name encoding. These are g_dir_open(),
96 * g_dir_read_name(), g_dir_rewind(), g_dir_close().
101 * @G_FILE_ERROR_EXIST: Operation not permitted; only the owner of
102 * the file (or other resource) or processes with special privileges
103 * can perform the operation.
104 * @G_FILE_ERROR_ISDIR: File is a directory; you cannot open a directory
105 * for writing, or create or remove hard links to it.
106 * @G_FILE_ERROR_ACCES: Permission denied; the file permissions do not
107 * allow the attempted operation.
108 * @G_FILE_ERROR_NAMETOOLONG: Filename too long.
109 * @G_FILE_ERROR_NOENT: No such file or directory. This is a "file
110 * doesn't exist" error for ordinary files that are referenced in
111 * contexts where they are expected to already exist.
112 * @G_FILE_ERROR_NOTDIR: A file that isn't a directory was specified when
113 * a directory is required.
114 * @G_FILE_ERROR_NXIO: No such device or address. The system tried to
115 * use the device represented by a file you specified, and it
116 * couldn't find the device. This can mean that the device file was
117 * installed incorrectly, or that the physical device is missing or
118 * not correctly attached to the computer.
119 * @G_FILE_ERROR_NODEV: The underlying file system of the specified file
120 * does not support memory mapping.
121 * @G_FILE_ERROR_ROFS: The directory containing the new link can't be
122 * modified because it's on a read-only file system.
123 * @G_FILE_ERROR_TXTBSY: Text file busy.
124 * @G_FILE_ERROR_FAULT: You passed in a pointer to bad memory.
125 * (GLib won't reliably return this, don't pass in pointers to bad
127 * @G_FILE_ERROR_LOOP: Too many levels of symbolic links were encountered
128 * in looking up a file name. This often indicates a cycle of symbolic
130 * @G_FILE_ERROR_NOSPC: No space left on device; write operation on a
131 * file failed because the disk is full.
132 * @G_FILE_ERROR_NOMEM: No memory available. The system cannot allocate
133 * more virtual memory because its capacity is full.
134 * @G_FILE_ERROR_MFILE: The current process has too many files open and
135 * can't open any more. Duplicate descriptors do count toward this
137 * @G_FILE_ERROR_NFILE: There are too many distinct file openings in the
139 * @G_FILE_ERROR_BADF: Bad file descriptor; for example, I/O on a
140 * descriptor that has been closed or reading from a descriptor open
141 * only for writing (or vice versa).
142 * @G_FILE_ERROR_INVAL: Invalid argument. This is used to indicate
143 * various kinds of problems with passing the wrong argument to a
145 * @G_FILE_ERROR_PIPE: Broken pipe; there is no process reading from the
146 * other end of a pipe. Every library function that returns this
147 * error code also generates a 'SIGPIPE' signal; this signal
148 * terminates the program if not handled or blocked. Thus, your
149 * program will never actually see this code unless it has handled
150 * or blocked 'SIGPIPE'.
151 * @G_FILE_ERROR_AGAIN: Resource temporarily unavailable; the call might
152 * work if you try again later.
153 * @G_FILE_ERROR_INTR: Interrupted function call; an asynchronous signal
154 * occurred and prevented completion of the call. When this
155 * happens, you should try the call again.
156 * @G_FILE_ERROR_IO: Input/output error; usually used for physical read
157 * or write errors. i.e. the disk or other physical device hardware
158 * is returning errors.
159 * @G_FILE_ERROR_PERM: Operation not permitted; only the owner of the
160 * file (or other resource) or processes with special privileges can
161 * perform the operation.
162 * @G_FILE_ERROR_NOSYS: Function not implemented; this indicates that
163 * the system is missing some functionality.
164 * @G_FILE_ERROR_FAILED: Does not correspond to a UNIX error code; this
165 * is the standard "failed for unspecified reason" error code present
166 * in all #GError error code enumerations. Returned if no specific
169 * Values corresponding to @errno codes returned from file operations
170 * on UNIX. Unlike @errno codes, GFileError values are available on
171 * all systems, even Windows. The exact meaning of each code depends
172 * on what sort of file operation you were performing; the UNIX
173 * documentation gives more details. The following error code descriptions
174 * come from the GNU C Library manual, and are under the copyright
177 * It's not very portable to make detailed assumptions about exactly
178 * which errors will be returned from a given operation. Some errors
179 * don't occur on some systems, etc., sometimes there are subtle
180 * differences in when a system will report a given error, etc.
186 * Error domain for file operations. Errors in this domain will
187 * be from the #GFileError enumeration. See #GError for information
193 * @G_FILE_TEST_IS_REGULAR: %TRUE if the file is a regular file
194 * (not a directory). Note that this test will also return %TRUE
195 * if the tested file is a symlink to a regular file.
196 * @G_FILE_TEST_IS_SYMLINK: %TRUE if the file is a symlink.
197 * @G_FILE_TEST_IS_DIR: %TRUE if the file is a directory.
198 * @G_FILE_TEST_IS_EXECUTABLE: %TRUE if the file is executable.
199 * @G_FILE_TEST_EXISTS: %TRUE if the file exists. It may or may not
202 * A test to perform on a file using g_file_test().
206 * g_mkdir_with_parents:
207 * @pathname: (type filename): a pathname in the GLib file name encoding
208 * @mode: permissions to use for newly created directories
210 * Create a directory if it doesn't already exist. Create intermediate
211 * parent directories as needed, too.
213 * Returns: 0 if the directory already exists, or was successfully
214 * created. Returns -1 if an error occurred, with errno set.
219 g_mkdir_with_parents (const gchar *pathname,
224 if (pathname == NULL || *pathname == '\0')
230 /* try to create the full path first */
231 if (g_mkdir (pathname, mode) == 0)
233 else if (errno == EEXIST)
235 if (!g_file_test (pathname, G_FILE_TEST_IS_DIR))
243 /* walk the full path and try creating each element */
244 fn = g_strdup (pathname);
246 if (g_path_is_absolute (fn))
247 p = (gchar *) g_path_skip_root (fn);
253 while (*p && !G_IS_DIR_SEPARATOR (*p))
261 if (!g_file_test (fn, G_FILE_TEST_EXISTS))
263 if (g_mkdir (fn, mode) == -1 && errno != EEXIST)
265 int errno_save = errno;
266 if (errno != ENOENT || !p)
274 else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
282 *p++ = G_DIR_SEPARATOR;
283 while (*p && G_IS_DIR_SEPARATOR (*p))
296 * @filename: (type filename): a filename to test in the
297 * GLib file name encoding
298 * @test: bitfield of #GFileTest flags
300 * Returns %TRUE if any of the tests in the bitfield @test are
301 * %TRUE. For example, `(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)`
302 * will return %TRUE if the file exists; the check whether it's a
303 * directory doesn't matter since the existence test is %TRUE. With
304 * the current set of available tests, there's no point passing in
305 * more than one test at a time.
307 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
308 * so for a symbolic link to a regular file g_file_test() will return
309 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
311 * Note, that for a dangling symbolic link g_file_test() will return
312 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
314 * You should never use g_file_test() to test whether it is safe
315 * to perform an operation, because there is always the possibility
316 * of the condition changing before you actually perform the operation.
317 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
318 * to know whether it is safe to write to a file without being
319 * tricked into writing into a different location. It doesn't work!
320 * |[<!-- language="C" -->
322 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
324 * fd = g_open (filename, O_WRONLY);
329 * Another thing to note is that %G_FILE_TEST_EXISTS and
330 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
331 * system call. This usually doesn't matter, but if your program
332 * is setuid or setgid it means that these tests will give you
333 * the answer for the real user ID and group ID, rather than the
334 * effective user ID and group ID.
336 * On Windows, there are no symlinks, so testing for
337 * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
338 * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
339 * its name indicates that it is executable, checking for well-known
340 * extensions and those listed in the `PATHEXT` environment variable.
342 * Returns: whether a test was %TRUE
345 g_file_test (const gchar *filename,
353 g_return_val_if_fail (filename != NULL, FALSE);
356 /* stuff missing in std vc6 api */
357 # ifndef INVALID_FILE_ATTRIBUTES
358 # define INVALID_FILE_ATTRIBUTES -1
360 # ifndef FILE_ATTRIBUTE_DEVICE
361 # define FILE_ATTRIBUTE_DEVICE 64
363 wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
365 if (wfilename == NULL)
368 attributes = GetFileAttributesW (wfilename);
372 if (attributes == INVALID_FILE_ATTRIBUTES)
375 if (test & G_FILE_TEST_EXISTS)
378 if (test & G_FILE_TEST_IS_REGULAR)
380 if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0)
384 if (test & G_FILE_TEST_IS_DIR)
386 if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
390 /* "while" so that we can exit this "loop" with a simple "break" */
391 while (test & G_FILE_TEST_IS_EXECUTABLE)
393 const gchar *lastdot = strrchr (filename, '.');
394 const gchar *pathext = NULL, *p;
400 if (_stricmp (lastdot, ".exe") == 0 ||
401 _stricmp (lastdot, ".cmd") == 0 ||
402 _stricmp (lastdot, ".bat") == 0 ||
403 _stricmp (lastdot, ".com") == 0)
406 /* Check if it is one of the types listed in %PATHEXT% */
408 pathext = g_getenv ("PATHEXT");
412 pathext = g_utf8_casefold (pathext, -1);
414 lastdot = g_utf8_casefold (lastdot, -1);
415 extlen = strlen (lastdot);
420 const gchar *q = strchr (p, ';');
423 if (extlen == q - p &&
424 memcmp (lastdot, p, extlen) == 0)
426 g_free ((gchar *) pathext);
427 g_free ((gchar *) lastdot);
436 g_free ((gchar *) pathext);
437 g_free ((gchar *) lastdot);
443 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
446 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
451 /* For root, on some POSIX systems, access (filename, X_OK)
452 * will succeed even if no executable bits are set on the
453 * file. We fall through to a stat test to avoid that.
457 test &= ~G_FILE_TEST_IS_EXECUTABLE;
459 if (test & G_FILE_TEST_IS_SYMLINK)
463 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
467 if (test & (G_FILE_TEST_IS_REGULAR |
469 G_FILE_TEST_IS_EXECUTABLE))
473 if (stat (filename, &s) == 0)
475 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
478 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
481 /* The extra test for root when access (file, X_OK) succeeds.
483 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
484 ((s.st_mode & S_IXOTH) ||
485 (s.st_mode & S_IXUSR) ||
486 (s.st_mode & S_IXGRP)))
495 G_DEFINE_QUARK (g-file-error-quark, g_file_error)
498 * g_file_error_from_errno:
499 * @err_no: an "errno" value
501 * Gets a #GFileError constant based on the passed-in @err_no.
503 * For example, if you pass in `EEXIST` this function returns
504 * %G_FILE_ERROR_EXIST. Unlike `errno` values, you can portably
505 * assume that all #GFileError values will exist.
507 * Normally a #GFileError value goes into a #GError returned
508 * from a function that manipulates files. So you would use
509 * g_file_error_from_errno() when constructing a #GError.
511 * Returns: #GFileError corresponding to the given @err_no
514 g_file_error_from_errno (gint err_no)
520 return G_FILE_ERROR_EXIST;
525 return G_FILE_ERROR_ISDIR;
530 return G_FILE_ERROR_ACCES;
535 return G_FILE_ERROR_NAMETOOLONG;
540 return G_FILE_ERROR_NOENT;
545 return G_FILE_ERROR_NOTDIR;
550 return G_FILE_ERROR_NXIO;
555 return G_FILE_ERROR_NODEV;
560 return G_FILE_ERROR_ROFS;
565 return G_FILE_ERROR_TXTBSY;
570 return G_FILE_ERROR_FAULT;
575 return G_FILE_ERROR_LOOP;
580 return G_FILE_ERROR_NOSPC;
585 return G_FILE_ERROR_NOMEM;
590 return G_FILE_ERROR_MFILE;
595 return G_FILE_ERROR_NFILE;
600 return G_FILE_ERROR_BADF;
605 return G_FILE_ERROR_INVAL;
610 return G_FILE_ERROR_PIPE;
615 return G_FILE_ERROR_AGAIN;
620 return G_FILE_ERROR_INTR;
625 return G_FILE_ERROR_IO;
630 return G_FILE_ERROR_PERM;
635 return G_FILE_ERROR_NOSYS;
639 return G_FILE_ERROR_FAILED;
644 format_error_message (const gchar *filename,
645 const gchar *format_string,
646 int saved_errno) G_GNUC_FORMAT(2);
648 #pragma GCC diagnostic push
649 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
652 format_error_message (const gchar *filename,
653 const gchar *format_string,
659 display_name = g_filename_display_name (filename);
660 msg = g_strdup_printf (format_string, display_name, g_strerror (saved_errno));
661 g_free (display_name);
666 #pragma GCC diagnostic pop
668 /* format string must have two '%s':
670 * - the place for the filename
671 * - the place for the strerror
674 set_file_error (GError **error,
675 const gchar *filename,
676 const gchar *format_string,
679 char *msg = format_error_message (filename, format_string, saved_errno);
681 g_set_error_literal (error, G_FILE_ERROR, g_file_error_from_errno (saved_errno),
687 get_contents_stdio (const gchar *filename,
694 gsize bytes; /* always <= sizeof(buf) */
696 gsize total_bytes = 0;
697 gsize total_allocated = 0;
699 gchar *display_filename;
701 g_assert (f != NULL);
707 bytes = fread (buf, 1, sizeof (buf), f);
710 if (total_bytes > G_MAXSIZE - bytes)
713 /* Possibility of overflow eliminated above. */
714 while (total_bytes + bytes >= total_allocated)
718 if (total_allocated > G_MAXSIZE / 2)
720 total_allocated *= 2;
724 total_allocated = MIN (bytes + 1, sizeof (buf));
727 tmp = g_try_realloc (str, total_allocated);
731 display_filename = g_filename_display_name (filename);
735 g_dngettext (GETTEXT_PACKAGE, "Could not allocate %lu byte to read file “%s”", "Could not allocate %lu bytes to read file “%s”", (gulong)total_allocated),
736 (gulong) total_allocated,
738 g_free (display_filename);
748 display_filename = g_filename_display_name (filename);
751 g_file_error_from_errno (save_errno),
752 _("Error reading file “%s”: %s"),
754 g_strerror (save_errno));
755 g_free (display_filename);
760 g_assert (str != NULL);
761 memcpy (str + total_bytes, buf, bytes);
763 total_bytes += bytes;
768 if (total_allocated == 0)
770 str = g_new (gchar, 1);
774 str[total_bytes] = '\0';
777 *length = total_bytes;
784 display_filename = g_filename_display_name (filename);
788 _("File “%s” is too large"),
790 g_free (display_filename);
803 get_contents_regfile (const gchar *filename,
804 struct stat *stat_buf,
814 gchar *display_filename;
816 size = stat_buf->st_size;
818 alloc_size = size + 1;
819 buf = g_try_malloc (alloc_size);
823 display_filename = g_filename_display_name (filename);
827 g_dngettext (GETTEXT_PACKAGE, "Could not allocate %lu byte to read file “%s”", "Could not allocate %lu bytes to read file “%s”", (gulong)alloc_size),
830 g_free (display_filename);
835 while (bytes_read < size)
839 rc = read (fd, buf + bytes_read, size - bytes_read);
845 int save_errno = errno;
848 display_filename = g_filename_display_name (filename);
851 g_file_error_from_errno (save_errno),
852 _("Failed to read from file “%s”: %s"),
854 g_strerror (save_errno));
855 g_free (display_filename);
865 buf[bytes_read] = '\0';
868 *length = bytes_read;
884 get_contents_posix (const gchar *filename,
889 struct stat stat_buf;
892 /* O_BINARY useful on Cygwin */
893 fd = open (filename, O_RDONLY|O_BINARY);
897 int saved_errno = errno;
900 set_file_error (error,
902 _("Failed to open file “%s”: %s"),
908 /* I don't think this will ever fail, aside from ENOMEM, but. */
909 if (fstat (fd, &stat_buf) < 0)
911 int saved_errno = errno;
913 set_file_error (error,
915 _("Failed to get attributes of file “%s”: fstat() failed: %s"),
922 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
924 gboolean retval = get_contents_regfile (filename,
938 f = fdopen (fd, "r");
942 int saved_errno = errno;
944 set_file_error (error,
946 _("Failed to open file “%s”: fdopen() failed: %s"),
952 retval = get_contents_stdio (filename, f, contents, length, error);
958 #else /* G_OS_WIN32 */
961 get_contents_win32 (const gchar *filename,
969 f = g_fopen (filename, "rb");
973 int saved_errno = errno;
975 set_file_error (error,
977 _("Failed to open file “%s”: %s"),
983 retval = get_contents_stdio (filename, f, contents, length, error);
991 * g_file_get_contents:
992 * @filename: (type filename): name of a file to read contents from, in the GLib file name encoding
993 * @contents: (out) (array length=length) (element-type guint8): location to store an allocated string, use g_free() to free
994 * the returned string
995 * @length: (nullable): location to store length in bytes of the contents, or %NULL
996 * @error: return location for a #GError, or %NULL
998 * Reads an entire file into allocated memory, with good error
1001 * If the call was successful, it returns %TRUE and sets @contents to the file
1002 * contents and @length to the length of the file contents in bytes. The string
1003 * stored in @contents will be nul-terminated, so for text files you can pass
1004 * %NULL for the @length argument. If the call was not successful, it returns
1005 * %FALSE and sets @error. The error domain is %G_FILE_ERROR. Possible error
1006 * codes are those in the #GFileError enumeration. In the error case,
1007 * @contents is set to %NULL and @length is set to zero.
1009 * Returns: %TRUE on success, %FALSE if an error occurred
1012 g_file_get_contents (const gchar *filename,
1017 g_return_val_if_fail (filename != NULL, FALSE);
1018 g_return_val_if_fail (contents != NULL, FALSE);
1025 return get_contents_win32 (filename, contents, length, error);
1027 return get_contents_posix (filename, contents, length, error);
1032 rename_file (const char *old_name,
1033 const char *new_name,
1038 if (g_rename (old_name, new_name) == -1)
1040 int save_errno = errno;
1041 gchar *display_old_name = g_filename_display_name (old_name);
1042 gchar *display_new_name = g_filename_display_name (new_name);
1046 g_file_error_from_errno (save_errno),
1047 _("Failed to rename file “%s” to “%s”: g_rename() failed: %s"),
1050 g_strerror (save_errno));
1052 g_free (display_old_name);
1053 g_free (display_new_name);
1058 /* In order to guarantee that the *new* contents of the file are seen in
1059 * future, fsync() the directory containing the file. Otherwise if the file
1060 * system was unmounted cleanly now, it would be undefined whether the old
1061 * or new contents of the file were visible after recovery.
1063 * This assumes the @old_name and @new_name are in the same directory. */
1067 gchar *dir = g_path_get_dirname (new_name);
1068 int dir_fd = g_open (dir, O_RDONLY, 0);
1073 g_close (dir_fd, NULL);
1078 #endif /* HAVE_FSYNC */
1084 fd_should_be_fsynced (int fd,
1085 const gchar *test_file,
1086 GFileSetContentsFlags flags)
1089 struct stat statbuf;
1091 /* If the final destination exists and is > 0 bytes, we want to sync the
1092 * newly written file to ensure the data is on disk when we rename over
1093 * the destination. Otherwise if we get a system crash we can lose both
1094 * the new and the old file on some filesystems. (I.E. those that don't
1095 * guarantee the data is written to the disk before the metadata.)
1097 * There is no difference (in file system terms) if the old file doesn’t
1098 * already exist, apart from the fact that if the system crashes and the new
1099 * data hasn’t been fsync()ed, there is only one bit of old data to lose (that
1100 * the file didn’t exist in the first place). In some situations, such as
1101 * trashing files, the old file never exists, so it seems reasonable to avoid
1102 * the fsync(). This is not a widely applicable optimisation though.
1104 if ((flags & (G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_DURABLE)) &&
1105 (flags & G_FILE_SET_CONTENTS_ONLY_EXISTING))
1108 if (g_lstat (test_file, &statbuf) == 0)
1109 return (statbuf.st_size > 0);
1110 else if (errno == ENOENT)
1113 return TRUE; /* lstat() failed; be cautious */
1117 return (flags & (G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_DURABLE));
1119 #else /* if !HAVE_FSYNC */
1121 #endif /* !HAVE_FSYNC */
1124 /* closes @fd once it’s finished (on success or error) */
1126 write_to_file (const gchar *contents,
1129 const gchar *dest_file,
1133 #ifdef HAVE_FALLOCATE
1136 /* We do this on a 'best effort' basis... It may not be supported
1137 * on the underlying filesystem.
1139 (void) fallocate (fd, 0, 0, length);
1146 s = write (fd, contents, MIN (length, G_MAXSSIZE));
1150 int saved_errno = errno;
1151 if (saved_errno == EINTR)
1155 set_file_error (err,
1156 dest_file, _("Failed to write file “%s”: write() failed: %s"),
1163 g_assert ((gsize) s <= length);
1172 if (do_fsync && g_fsync (fd) != 0)
1174 int saved_errno = errno;
1176 set_file_error (err,
1177 dest_file, _("Failed to write file “%s”: fsync() failed: %s"),
1186 if (!g_close (fd, err))
1193 * g_file_set_contents:
1194 * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1196 * @contents: (array length=length) (element-type guint8): string to write to the file
1197 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1198 * @error: return location for a #GError, or %NULL
1200 * Writes all of @contents to a file named @filename. This is a convenience
1201 * wrapper around calling g_file_set_contents_full() with `flags` set to
1202 * `G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING` and
1203 * `mode` set to `0666`.
1205 * Returns: %TRUE on success, %FALSE if an error occurred
1210 g_file_set_contents (const gchar *filename,
1211 const gchar *contents,
1215 return g_file_set_contents_full (filename, contents, length,
1216 G_FILE_SET_CONTENTS_CONSISTENT |
1217 G_FILE_SET_CONTENTS_ONLY_EXISTING,
1222 * g_file_set_contents_full:
1223 * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1225 * @contents: (array length=length) (element-type guint8): string to write to the file
1226 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1227 * @flags: flags controlling the safety vs speed of the operation
1228 * @mode: file mode, as passed to `open()`; typically this will be `0666`
1229 * @error: return location for a #GError, or %NULL
1231 * Writes all of @contents to a file named @filename, with good error checking.
1232 * If a file called @filename already exists it will be overwritten.
1234 * @flags control the properties of the write operation: whether it’s atomic,
1235 * and what the tradeoff is between returning quickly or being resilient to
1238 * As this function performs file I/O, it is recommended to not call it anywhere
1239 * where blocking would cause problems, such as in the main loop of a graphical
1240 * application. In particular, if @flags has any value other than
1241 * %G_FILE_SET_CONTENTS_NONE then this function may call `fsync()`.
1243 * If %G_FILE_SET_CONTENTS_CONSISTENT is set in @flags, the operation is atomic
1244 * in the sense that it is first written to a temporary file which is then
1245 * renamed to the final name.
1249 * - On UNIX, if @filename already exists hard links to @filename will break.
1250 * Also since the file is recreated, existing permissions, access control
1251 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1252 * the link itself will be replaced, not the linked file.
1254 * - On UNIX, if @filename already exists and is non-empty, and if the system
1255 * supports it (via a journalling filesystem or equivalent), and if
1256 * %G_FILE_SET_CONTENTS_CONSISTENT is set in @flags, the `fsync()` call (or
1257 * equivalent) will be used to ensure atomic replacement: @filename
1258 * will contain either its old contents or @contents, even in the face of
1259 * system power loss, the disk being unsafely removed, etc.
1261 * - On UNIX, if @filename does not already exist or is empty, there is a
1262 * possibility that system power loss etc. after calling this function will
1263 * leave @filename empty or full of NUL bytes, depending on the underlying
1264 * filesystem, unless %G_FILE_SET_CONTENTS_DURABLE and
1265 * %G_FILE_SET_CONTENTS_CONSISTENT are set in @flags.
1267 * - On Windows renaming a file will not remove an existing file with the
1268 * new name, so on Windows there is a race condition between the existing
1269 * file being removed and the temporary file being renamed.
1271 * - On Windows there is no way to remove a file that is open to some
1272 * process, or mapped into memory. Thus, this function will fail if
1273 * @filename already exists and is open.
1275 * If the call was successful, it returns %TRUE. If the call was not successful,
1276 * it returns %FALSE and sets @error. The error domain is %G_FILE_ERROR.
1277 * Possible error codes are those in the #GFileError enumeration.
1279 * Note that the name for the temporary file is constructed by appending up
1280 * to 7 characters to @filename.
1282 * If the file didn’t exist before and is created, it will be given the
1283 * permissions from @mode. Otherwise, the permissions of the existing file may
1284 * be changed to @mode depending on @flags, or they may remain unchanged.
1286 * Returns: %TRUE on success, %FALSE if an error occurred
1291 g_file_set_contents_full (const gchar *filename,
1292 const gchar *contents,
1294 GFileSetContentsFlags flags,
1298 g_return_val_if_fail (filename != NULL, FALSE);
1299 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1300 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1301 g_return_val_if_fail (length >= -1, FALSE);
1303 /* @flags are handled as follows:
1304 * - %G_FILE_SET_CONTENTS_NONE: write directly to @filename, no fsync()s
1305 * - %G_FILE_SET_CONTENTS_CONSISTENT: write to temp file, fsync() it, rename()
1306 * - %G_FILE_SET_CONTENTS_CONSISTENT | ONLY_EXISTING: as above, but skip the
1307 * fsync() if @filename doesn’t exist or is empty
1308 * - %G_FILE_SET_CONTENTS_DURABLE: write directly to @filename, fsync() it
1309 * - %G_FILE_SET_CONTENTS_DURABLE | ONLY_EXISTING: as above, but skip the
1310 * fsync() if @filename doesn’t exist or is empty
1311 * - %G_FILE_SET_CONTENTS_CONSISTENT | DURABLE: write to temp file, fsync()
1312 * it, rename(), fsync() containing directory
1313 * - %G_FILE_SET_CONTENTS_CONSISTENT | DURABLE | ONLY_EXISTING: as above, but
1314 * skip both fsync()s if @filename doesn’t exist or is empty
1318 length = strlen (contents);
1320 if (flags & G_FILE_SET_CONTENTS_CONSISTENT)
1322 gchar *tmp_filename = NULL;
1323 GError *rename_error = NULL;
1328 tmp_filename = g_strdup_printf ("%s.XXXXXX", filename);
1331 fd = g_mkstemp_full (tmp_filename, O_RDWR | O_BINARY, mode);
1335 int saved_errno = errno;
1337 set_file_error (error,
1338 tmp_filename, _("Failed to create file “%s”: %s"),
1341 goto consistent_out;
1344 do_fsync = fd_should_be_fsynced (fd, filename, flags);
1345 if (!write_to_file (contents, length, g_steal_fd (&fd), tmp_filename, do_fsync, error))
1347 g_unlink (tmp_filename);
1349 goto consistent_out;
1352 if (!rename_file (tmp_filename, filename, do_fsync, &rename_error))
1356 g_unlink (tmp_filename);
1357 g_propagate_error (error, rename_error);
1359 goto consistent_out;
1361 #else /* G_OS_WIN32 */
1363 /* Renaming failed, but on Windows this may just mean
1364 * the file already exists. So if the target file
1365 * exists, try deleting it and do the rename again.
1367 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1369 g_unlink (tmp_filename);
1370 g_propagate_error (error, rename_error);
1372 goto consistent_out;
1375 g_error_free (rename_error);
1377 if (g_unlink (filename) == -1)
1379 int saved_errno = errno;
1381 set_file_error (error,
1383 _("Existing file “%s” could not be removed: g_unlink() failed: %s"),
1385 g_unlink (tmp_filename);
1387 goto consistent_out;
1390 if (!rename_file (tmp_filename, filename, flags, error))
1392 g_unlink (tmp_filename);
1394 goto consistent_out;
1397 #endif /* G_OS_WIN32 */
1403 g_free (tmp_filename);
1412 open_flags = O_RDWR | O_BINARY | O_CREAT | O_CLOEXEC;
1414 /* Windows doesn’t have symlinks, so O_NOFOLLOW is unnecessary there. */
1415 open_flags |= O_NOFOLLOW;
1419 direct_fd = g_open (filename, open_flags, mode);
1423 int saved_errno = errno;
1426 /* ELOOP indicates that @filename is a symlink, since we used
1427 * O_NOFOLLOW (alternately it could indicate that @filename contains
1428 * looping or too many symlinks). In either case, try again on the
1429 * %G_FILE_SET_CONTENTS_CONSISTENT code path.
1431 * FreeBSD uses EMLINK instead of ELOOP
1432 * (https://www.freebsd.org/cgi/man.cgi?query=open&sektion=2#STANDARDS),
1433 * and NetBSD uses EFTYPE
1434 * (https://netbsd.gw.com/cgi-bin/man-cgi?open+2+NetBSD-current). */
1435 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1436 if (saved_errno == EMLINK)
1437 #elif defined(__NetBSD__)
1438 if (saved_errno == EFTYPE)
1440 if (saved_errno == ELOOP)
1442 return g_file_set_contents_full (filename, contents, length,
1443 flags | G_FILE_SET_CONTENTS_CONSISTENT,
1445 #endif /* O_NOFOLLOW */
1448 set_file_error (error,
1449 filename, _("Failed to open file “%s”: %s"),
1454 do_fsync = fd_should_be_fsynced (direct_fd, filename, flags);
1455 if (!write_to_file (contents, length, g_steal_fd (&direct_fd), filename,
1464 * get_tmp_file based on the mkstemp implementation from the GNU C library.
1465 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1467 typedef gint (*GTmpFileCallback) (const gchar *, gint, gint);
1470 get_tmp_file (gchar *tmpl,
1477 static const char letters[] =
1478 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1479 static const int NLETTERS = sizeof (letters) - 1;
1482 static int counter = 0;
1484 g_return_val_if_fail (tmpl != NULL, -1);
1486 /* find the last occurrence of "XXXXXX" */
1487 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1489 if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1495 /* Get some more or less random data. */
1496 now_us = g_get_real_time ();
1497 value = ((now_us % G_USEC_PER_SEC) ^ (now_us / G_USEC_PER_SEC)) + counter++;
1499 for (count = 0; count < 100; value += 7777, ++count)
1503 /* Fill in the random bits. */
1504 XXXXXX[0] = letters[v % NLETTERS];
1506 XXXXXX[1] = letters[v % NLETTERS];
1508 XXXXXX[2] = letters[v % NLETTERS];
1510 XXXXXX[3] = letters[v % NLETTERS];
1512 XXXXXX[4] = letters[v % NLETTERS];
1514 XXXXXX[5] = letters[v % NLETTERS];
1516 fd = f (tmpl, flags, mode);
1520 else if (errno != EEXIST)
1521 /* Any other error will apply also to other names we might
1522 * try, and there are 2^32 or so of them, so give up now.
1527 /* We got out of the loop because we ran out of combinations to try. */
1532 /* Some GTmpFileCallback implementations.
1534 * Note: we cannot use open() or g_open() directly because even though
1535 * they appear compatible, they may be vararg functions and calling
1536 * varargs functions through a non-varargs type is undefined.
1539 wrap_g_mkdir (const gchar *filename,
1540 int flags G_GNUC_UNUSED,
1543 /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1544 return g_mkdir (filename, mode);
1548 wrap_g_open (const gchar *filename,
1552 return g_open (filename, flags, mode);
1556 * g_mkdtemp_full: (skip)
1557 * @tmpl: (type filename): template directory name
1558 * @mode: permissions to create the temporary directory with
1560 * Creates a temporary directory. See the mkdtemp() documentation
1561 * on most UNIX-like systems.
1563 * The parameter is a string that should follow the rules for
1564 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1565 * g_mkdtemp_full() is slightly more flexible than mkdtemp() in that the
1566 * sequence does not have to occur at the very end of the template
1567 * and you can pass a @mode. The X string will be modified to form
1568 * the name of a directory that didn't exist. The string should be
1569 * in the GLib file name encoding. Most importantly, on Windows it
1570 * should be in UTF-8.
1572 * If you are going to be creating a temporary directory inside the
1573 * directory returned by g_get_tmp_dir(), you might want to use
1574 * g_dir_make_tmp() instead.
1576 * Returns: (nullable) (type filename): A pointer to @tmpl, which has been
1577 * modified to hold the directory name. In case of errors, %NULL is
1578 * returned, and %errno will be set.
1583 g_mkdtemp_full (gchar *tmpl,
1586 if (get_tmp_file (tmpl, wrap_g_mkdir, 0, mode) == -1)
1594 * @tmpl: (type filename): template directory name
1596 * Creates a temporary directory. See the mkdtemp() documentation
1597 * on most UNIX-like systems.
1599 * The parameter is a string that should follow the rules for
1600 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1601 * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1602 * sequence does not have to occur at the very end of the template.
1603 * The X string will be modified to form the name of a directory that
1605 * The string should be in the GLib file name encoding. Most importantly,
1606 * on Windows it should be in UTF-8.
1608 * If you are going to be creating a temporary directory inside the
1609 * directory returned by g_get_tmp_dir(), you might want to use
1610 * g_dir_make_tmp() instead.
1612 * Returns: (nullable) (type filename): A pointer to @tmpl, which has been
1613 * modified to hold the directory name. In case of errors, %NULL is
1614 * returned and %errno will be set.
1619 g_mkdtemp (gchar *tmpl)
1621 return g_mkdtemp_full (tmpl, 0700);
1625 * g_mkstemp_full: (skip)
1626 * @tmpl: (type filename): template filename
1627 * @flags: flags to pass to an open() call in addition to O_EXCL
1628 * and O_CREAT, which are passed automatically
1629 * @mode: permissions to create the temporary file with
1631 * Opens a temporary file. See the mkstemp() documentation
1632 * on most UNIX-like systems.
1634 * The parameter is a string that should follow the rules for
1635 * mkstemp() templates, i.e. contain the string "XXXXXX".
1636 * g_mkstemp_full() is slightly more flexible than mkstemp()
1637 * in that the sequence does not have to occur at the very end of the
1638 * template and you can pass a @mode and additional @flags. The X
1639 * string will be modified to form the name of a file that didn't exist.
1640 * The string should be in the GLib file name encoding. Most importantly,
1641 * on Windows it should be in UTF-8.
1643 * Returns: A file handle (as from open()) to the file
1644 * opened for reading and writing. The file handle should be
1645 * closed with close(). In case of errors, -1 is returned
1646 * and %errno will be set.
1651 g_mkstemp_full (gchar *tmpl,
1655 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1656 return get_tmp_file (tmpl, wrap_g_open,
1657 flags | O_CREAT | O_EXCL, mode);
1662 * @tmpl: (type filename): template filename
1664 * Opens a temporary file. See the mkstemp() documentation
1665 * on most UNIX-like systems.
1667 * The parameter is a string that should follow the rules for
1668 * mkstemp() templates, i.e. contain the string "XXXXXX".
1669 * g_mkstemp() is slightly more flexible than mkstemp() in that the
1670 * sequence does not have to occur at the very end of the template.
1671 * The X string will be modified to form the name of a file that
1672 * didn't exist. The string should be in the GLib file name encoding.
1673 * Most importantly, on Windows it should be in UTF-8.
1675 * Returns: A file handle (as from open()) to the file
1676 * opened for reading and writing. The file is opened in binary
1677 * mode on platforms where there is a difference. The file handle
1678 * should be closed with close(). In case of errors, -1 is
1679 * returned and %errno will be set.
1682 g_mkstemp (gchar *tmpl)
1684 return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1688 g_get_tmp_name (const gchar *tmpl,
1704 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1706 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1710 gchar *display_tmpl = g_filename_display_name (tmpl);
1717 G_FILE_ERROR_FAILED,
1718 _("Template “%s” invalid, should not contain a “%s”"),
1720 g_free (display_tmpl);
1725 if (strstr (tmpl, "XXXXXX") == NULL)
1727 gchar *display_tmpl = g_filename_display_name (tmpl);
1730 G_FILE_ERROR_FAILED,
1731 _("Template “%s” doesn’t contain XXXXXX"),
1733 g_free (display_tmpl);
1737 tmpdir = g_get_tmp_dir ();
1739 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1742 sep = G_DIR_SEPARATOR_S;
1744 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1746 retval = get_tmp_file (fulltemplate, f, flags, mode);
1749 int saved_errno = errno;
1751 set_file_error (error,
1753 _("Failed to create file “%s”: %s"),
1755 g_free (fulltemplate);
1759 *name_used = fulltemplate;
1766 * @tmpl: (type filename) (nullable): Template for file name, as in
1767 * g_mkstemp(), basename only, or %NULL for a default template
1768 * @name_used: (out) (type filename): location to store actual name used,
1770 * @error: return location for a #GError
1772 * Opens a file for writing in the preferred directory for temporary
1773 * files (as returned by g_get_tmp_dir()).
1775 * @tmpl should be a string in the GLib file name encoding containing
1776 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1777 * However, unlike these functions, the template should only be a
1778 * basename, no directory components are allowed. If template is
1779 * %NULL, a default template is used.
1781 * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
1782 * modified, and might thus be a read-only literal string.
1784 * Upon success, and if @name_used is non-%NULL, the actual name used
1785 * is returned in @name_used. This string should be freed with g_free()
1786 * when not needed any longer. The returned name is in the GLib file
1789 * Returns: A file handle (as from open()) to the file opened for
1790 * reading and writing. The file is opened in binary mode on platforms
1791 * where there is a difference. The file handle should be closed with
1792 * close(). In case of errors, -1 is returned and @error will be set.
1795 g_file_open_tmp (const gchar *tmpl,
1799 gchar *fulltemplate;
1802 g_return_val_if_fail (error == NULL || *error == NULL, -1);
1804 result = g_get_tmp_name (tmpl, &fulltemplate,
1806 O_CREAT | O_EXCL | O_RDWR | O_BINARY,
1812 *name_used = fulltemplate;
1814 g_free (fulltemplate);
1822 * @tmpl: (type filename) (nullable): Template for directory name,
1823 * as in g_mkdtemp(), basename only, or %NULL for a default template
1824 * @error: return location for a #GError
1826 * Creates a subdirectory in the preferred directory for temporary
1827 * files (as returned by g_get_tmp_dir()).
1829 * @tmpl should be a string in the GLib file name encoding containing
1830 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1831 * However, unlike these functions, the template should only be a
1832 * basename, no directory components are allowed. If template is
1833 * %NULL, a default template is used.
1835 * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
1836 * modified, and might thus be a read-only literal string.
1838 * Returns: (type filename) (transfer full): The actual name used. This string
1839 * should be freed with g_free() when not needed any longer and is
1840 * is in the GLib file name encoding. In case of errors, %NULL is
1841 * returned and @error will be set.
1846 g_dir_make_tmp (const gchar *tmpl,
1849 gchar *fulltemplate;
1851 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1853 if (g_get_tmp_name (tmpl, &fulltemplate, wrap_g_mkdir, 0, 0700, error) == -1)
1856 return fulltemplate;
1860 g_build_path_va (const gchar *separator,
1861 const gchar *first_element,
1866 gint separator_len = strlen (separator);
1867 gboolean is_first = TRUE;
1868 gboolean have_leading = FALSE;
1869 const gchar *single_element = NULL;
1870 const gchar *next_element;
1871 const gchar *last_trailing = NULL;
1874 result = g_string_new (NULL);
1877 next_element = str_array[i++];
1879 next_element = first_element;
1883 const gchar *element;
1889 element = next_element;
1891 next_element = str_array[i++];
1893 next_element = va_arg (*args, gchar *);
1898 /* Ignore empty elements */
1906 while (strncmp (start, separator, separator_len) == 0)
1907 start += separator_len;
1910 end = start + strlen (start);
1914 while (end >= start + separator_len &&
1915 strncmp (end - separator_len, separator, separator_len) == 0)
1916 end -= separator_len;
1918 last_trailing = end;
1919 while (last_trailing >= element + separator_len &&
1920 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1921 last_trailing -= separator_len;
1925 /* If the leading and trailing separator strings are in the
1926 * same element and overlap, the result is exactly that element
1928 if (last_trailing <= start)
1929 single_element = element;
1931 g_string_append_len (result, element, start - element);
1932 have_leading = TRUE;
1935 single_element = NULL;
1942 g_string_append (result, separator);
1944 g_string_append_len (result, start, end - start);
1950 g_string_free (result, TRUE);
1951 return g_strdup (single_element);
1956 g_string_append (result, last_trailing);
1958 return g_string_free (result, FALSE);
1964 * @separator: a string used to separator the elements of the path.
1965 * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
1966 * array of strings containing the path elements.
1968 * Behaves exactly like g_build_path(), but takes the path elements
1969 * as a string array, instead of varargs. This function is mainly
1970 * meant for language bindings.
1972 * Returns: (type filename) (transfer full): a newly-allocated string that
1973 * must be freed with g_free().
1978 g_build_pathv (const gchar *separator,
1984 return g_build_path_va (separator, NULL, NULL, args);
1990 * @separator: (type filename): a string used to separator the elements of the path.
1991 * @first_element: (type filename): the first element in the path
1992 * @...: remaining elements in path, terminated by %NULL
1994 * Creates a path from a series of elements using @separator as the
1995 * separator between elements. At the boundary between two elements,
1996 * any trailing occurrences of separator in the first element, or
1997 * leading occurrences of separator in the second element are removed
1998 * and exactly one copy of the separator is inserted.
2000 * Empty elements are ignored.
2002 * The number of leading copies of the separator on the result is
2003 * the same as the number of leading copies of the separator on
2004 * the first non-empty element.
2006 * The number of trailing copies of the separator on the result is
2007 * the same as the number of trailing copies of the separator on
2008 * the last non-empty element. (Determination of the number of
2009 * trailing copies is done without stripping leading copies, so
2010 * if the separator is `ABA`, then `ABABA` has 1 trailing copy.)
2012 * However, if there is only a single non-empty element, and there
2013 * are no characters in that element not part of the leading or
2014 * trailing separators, then the result is exactly the original value
2017 * Other than for determination of the number of leading and trailing
2018 * copies of the separator, elements consisting only of copies
2019 * of the separator are ignored.
2021 * Returns: (type filename) (transfer full): a newly-allocated string that
2022 * must be freed with g_free().
2025 g_build_path (const gchar *separator,
2026 const gchar *first_element,
2032 g_return_val_if_fail (separator != NULL, NULL);
2034 va_start (args, first_element);
2035 str = g_build_path_va (separator, first_element, &args, NULL);
2044 g_build_pathname_va (const gchar *first_element,
2048 /* Code copied from g_build_pathv(), and modified to use two
2049 * alternative single-character separators.
2052 gboolean is_first = TRUE;
2053 gboolean have_leading = FALSE;
2054 const gchar *single_element = NULL;
2055 const gchar *next_element;
2056 const gchar *last_trailing = NULL;
2057 gchar current_separator = '\\';
2060 result = g_string_new (NULL);
2063 next_element = str_array[i++];
2065 next_element = first_element;
2069 const gchar *element;
2075 element = next_element;
2077 next_element = str_array[i++];
2079 next_element = va_arg (*args, gchar *);
2084 /* Ignore empty elements */
2093 (*start == '\\' || *start == '/'))
2095 current_separator = *start;
2100 end = start + strlen (start);
2104 while (end >= start + 1 &&
2105 (end[-1] == '\\' || end[-1] == '/'))
2107 current_separator = end[-1];
2111 last_trailing = end;
2112 while (last_trailing >= element + 1 &&
2113 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
2118 /* If the leading and trailing separator strings are in the
2119 * same element and overlap, the result is exactly that element
2121 if (last_trailing <= start)
2122 single_element = element;
2124 g_string_append_len (result, element, start - element);
2125 have_leading = TRUE;
2128 single_element = NULL;
2135 g_string_append_len (result, ¤t_separator, 1);
2137 g_string_append_len (result, start, end - start);
2143 g_string_free (result, TRUE);
2144 return g_strdup (single_element);
2149 g_string_append (result, last_trailing);
2151 return g_string_free (result, FALSE);
2158 g_build_filename_va (const gchar *first_argument,
2165 str = g_build_path_va (G_DIR_SEPARATOR_S, first_argument, args, str_array);
2167 str = g_build_pathname_va (first_argument, args, str_array);
2174 * g_build_filename_valist:
2175 * @first_element: (type filename): the first element in the path
2176 * @args: va_list of remaining elements in path
2178 * Behaves exactly like g_build_filename(), but takes the path elements
2179 * as a va_list. This function is mainly meant for language bindings.
2181 * Returns: (type filename) (transfer full): a newly-allocated string that
2182 * must be freed with g_free().
2187 g_build_filename_valist (const gchar *first_element,
2190 g_return_val_if_fail (first_element != NULL, NULL);
2192 return g_build_filename_va (first_element, args, NULL);
2196 * g_build_filenamev:
2197 * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
2198 * array of strings containing the path elements.
2200 * Behaves exactly like g_build_filename(), but takes the path elements
2201 * as a string array, instead of varargs. This function is mainly
2202 * meant for language bindings.
2204 * Returns: (type filename) (transfer full): a newly-allocated string that
2205 * must be freed with g_free().
2210 g_build_filenamev (gchar **args)
2212 return g_build_filename_va (NULL, NULL, args);
2217 * @first_element: (type filename): the first element in the path
2218 * @...: remaining elements in path, terminated by %NULL
2220 * Creates a filename from a series of elements using the correct
2221 * separator for filenames.
2223 * On Unix, this function behaves identically to `g_build_path
2224 * (G_DIR_SEPARATOR_S, first_element, ....)`.
2226 * On Windows, it takes into account that either the backslash
2227 * (`\` or slash (`/`) can be used as separator in filenames, but
2228 * otherwise behaves as on UNIX. When file pathname separators need
2229 * to be inserted, the one that last previously occurred in the
2230 * parameters (reading from left to right) is used.
2232 * No attempt is made to force the resulting filename to be an absolute
2233 * path. If the first element is a relative path, the result will
2234 * be a relative path.
2236 * Returns: (type filename) (transfer full): a newly-allocated string that
2237 * must be freed with g_free().
2240 g_build_filename (const gchar *first_element,
2246 va_start (args, first_element);
2247 str = g_build_filename_va (first_element, &args, NULL);
2255 * @filename: (type filename): the symbolic link
2256 * @error: return location for a #GError
2258 * Reads the contents of the symbolic link @filename like the POSIX
2259 * readlink() function.
2261 * The returned string is in the encoding used
2262 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
2264 * The returned string may also be a relative path. Use g_build_filename() to
2265 * convert it to an absolute path:
2267 * g_autoptr(GError) local_error = NULL;
2268 * g_autofree gchar *link_target = g_file_read_link ("/etc/localtime", &local_error);
2270 * if (local_error != NULL)
2271 * g_error ("Error reading link: %s", local_error->message);
2273 * if (!g_path_is_absolute (link_target))
2275 * g_autofree gchar *absolute_link_target = g_build_filename ("/etc", link_target, NULL);
2276 * g_free (link_target);
2277 * link_target = g_steal_pointer (&absolute_link_target);
2281 * Returns: (type filename) (transfer full): A newly-allocated string with
2282 * the contents of the symbolic link, or %NULL if an error occurred.
2287 g_file_read_link (const gchar *filename,
2290 #if defined (HAVE_READLINK)
2295 g_return_val_if_fail (filename != NULL, NULL);
2296 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2299 buffer = g_malloc (size);
2303 read_size = readlink (filename, buffer, size);
2306 int saved_errno = errno;
2308 set_file_error (error,
2310 _("Failed to read the symbolic link “%s”: %s"),
2316 if ((size_t) read_size < size)
2318 buffer[read_size] = 0;
2323 buffer = g_realloc (buffer, size);
2325 #elif defined (G_OS_WIN32)
2329 g_return_val_if_fail (filename != NULL, NULL);
2330 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2332 read_size = g_win32_readlink_utf8 (filename, NULL, 0, &buffer, TRUE);
2335 int saved_errno = errno;
2337 set_file_error (error,
2339 _("Failed to read the symbolic link “%s”: %s"),
2343 else if (read_size == 0)
2348 g_return_val_if_fail (filename != NULL, NULL);
2349 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2351 g_set_error_literal (error,
2354 _("Symbolic links not supported"));
2361 * g_path_is_absolute:
2362 * @file_name: (type filename): a file name
2364 * Returns %TRUE if the given @file_name is an absolute file name.
2365 * Note that this is a somewhat vague concept on Windows.
2367 * On POSIX systems, an absolute file name is well-defined. It always
2368 * starts from the single root directory. For example "/usr/local".
2370 * On Windows, the concepts of current drive and drive-specific
2371 * current directory introduce vagueness. This function interprets as
2372 * an absolute file name one that either begins with a directory
2373 * separator such as "\Users\tml" or begins with the root on a drive,
2374 * for example "C:\Windows". The first case also includes UNC paths
2375 * such as "\\\\myserver\docs\foo". In all cases, either slashes or
2376 * backslashes are accepted.
2378 * Note that a file name relative to the current drive root does not
2379 * truly specify a file uniquely over time and across processes, as
2380 * the current drive is a per-process value and can be changed.
2382 * File names relative the current directory on some specific drive,
2383 * such as "D:foo/bar", are not interpreted as absolute by this
2384 * function, but they obviously are not relative to the normal current
2385 * directory as returned by getcwd() or g_get_current_dir()
2386 * either. Such paths should be avoided, or need to be handled using
2387 * Windows-specific code.
2389 * Returns: %TRUE if @file_name is absolute
2392 g_path_is_absolute (const gchar *file_name)
2394 g_return_val_if_fail (file_name != NULL, FALSE);
2396 if (G_IS_DIR_SEPARATOR (file_name[0]))
2400 /* Recognize drive letter on native Windows */
2401 if (g_ascii_isalpha (file_name[0]) &&
2402 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
2411 * @file_name: (type filename): a file name
2413 * Returns a pointer into @file_name after the root component,
2414 * i.e. after the "/" in UNIX or "C:\" under Windows. If @file_name
2415 * is not an absolute path it returns %NULL.
2417 * Returns: (type filename) (nullable): a pointer into @file_name after the
2421 g_path_skip_root (const gchar *file_name)
2423 g_return_val_if_fail (file_name != NULL, NULL);
2425 #ifdef G_PLATFORM_WIN32
2426 /* Skip \\server\share or //server/share */
2427 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2428 G_IS_DIR_SEPARATOR (file_name[1]) &&
2430 !G_IS_DIR_SEPARATOR (file_name[2]))
2433 p = strchr (file_name + 2, G_DIR_SEPARATOR);
2439 q = strchr (file_name + 2, '/');
2440 if (p == NULL || (q != NULL && q < p))
2445 if (p && p > file_name + 2 && p[1])
2449 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
2452 /* Possibly skip a backslash after the share name */
2453 if (G_IS_DIR_SEPARATOR (file_name[0]))
2456 return (gchar *)file_name;
2461 /* Skip initial slashes */
2462 if (G_IS_DIR_SEPARATOR (file_name[0]))
2464 while (G_IS_DIR_SEPARATOR (file_name[0]))
2466 return (gchar *)file_name;
2471 if (g_ascii_isalpha (file_name[0]) &&
2472 file_name[1] == ':' &&
2473 G_IS_DIR_SEPARATOR (file_name[2]))
2474 return (gchar *)file_name + 3;
2482 * @file_name: (type filename): the name of the file
2484 * Gets the name of the file without any leading directory
2485 * components. It returns a pointer into the given file name
2488 * Returns: (type filename): the name of the file without any leading
2489 * directory components
2491 * Deprecated:2.2: Use g_path_get_basename() instead, but notice
2492 * that g_path_get_basename() allocates new memory for the
2493 * returned string, unlike this function which returns a pointer
2494 * into the argument.
2497 g_basename (const gchar *file_name)
2501 g_return_val_if_fail (file_name != NULL, NULL);
2503 base = strrchr (file_name, G_DIR_SEPARATOR);
2508 q = strrchr (file_name, '/');
2509 if (base == NULL || (q != NULL && q > base))
2518 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2519 return (gchar*) file_name + 2;
2522 return (gchar*) file_name;
2526 * g_path_get_basename:
2527 * @file_name: (type filename): the name of the file
2529 * Gets the last component of the filename.
2531 * If @file_name ends with a directory separator it gets the component
2532 * before the last slash. If @file_name consists only of directory
2533 * separators (and on Windows, possibly a drive letter), a single
2534 * separator is returned. If @file_name is empty, it gets ".".
2536 * Returns: (type filename) (transfer full): a newly allocated string
2537 * containing the last component of the filename
2540 g_path_get_basename (const gchar *file_name)
2543 gssize last_nonslash;
2547 g_return_val_if_fail (file_name != NULL, NULL);
2549 if (file_name[0] == '\0')
2550 return g_strdup (".");
2552 last_nonslash = strlen (file_name) - 1;
2554 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
2557 if (last_nonslash == -1)
2558 /* string only containing slashes */
2559 return g_strdup (G_DIR_SEPARATOR_S);
2562 if (last_nonslash == 1 &&
2563 g_ascii_isalpha (file_name[0]) &&
2564 file_name[1] == ':')
2565 /* string only containing slashes and a drive */
2566 return g_strdup (G_DIR_SEPARATOR_S);
2568 base = last_nonslash;
2570 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
2575 g_ascii_isalpha (file_name[0]) &&
2576 file_name[1] == ':')
2578 #endif /* G_OS_WIN32 */
2580 len = last_nonslash - base;
2581 retval = g_malloc (len + 1);
2582 memcpy (retval, file_name + (base + 1), len);
2583 retval [len] = '\0';
2590 * @file_name: (type filename): the name of the file
2592 * Gets the directory components of a file name.
2594 * If the file name has no directory components "." is returned.
2595 * The returned string should be freed when no longer needed.
2597 * Returns: (type filename) (transfer full): the directory components of the file
2599 * Deprecated: use g_path_get_dirname() instead
2603 * g_path_get_dirname:
2604 * @file_name: (type filename): the name of the file
2606 * Gets the directory components of a file name. For example, the directory
2607 * component of `/usr/bin/test` is `/usr/bin`. The directory component of `/`
2610 * If the file name has no directory components "." is returned.
2611 * The returned string should be freed when no longer needed.
2613 * Returns: (type filename) (transfer full): the directory components of the file
2616 g_path_get_dirname (const gchar *file_name)
2621 g_return_val_if_fail (file_name != NULL, NULL);
2623 base = strrchr (file_name, G_DIR_SEPARATOR);
2628 q = strrchr (file_name, '/');
2629 if (base == NULL || (q != NULL && q > base))
2637 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2639 gchar drive_colon_dot[4];
2641 drive_colon_dot[0] = file_name[0];
2642 drive_colon_dot[1] = ':';
2643 drive_colon_dot[2] = '.';
2644 drive_colon_dot[3] = '\0';
2646 return g_strdup (drive_colon_dot);
2649 return g_strdup (".");
2652 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
2656 /* base points to the char before the last slash.
2658 * In case file_name is the root of a drive (X:\) or a child of the
2659 * root of a drive (X:\foo), include the slash.
2661 * In case file_name is the root share of an UNC path
2662 * (\\server\share), add a slash, returning \\server\share\ .
2664 * In case file_name is a direct child of a share in an UNC path
2665 * (\\server\share\foo), include the slash after the share name,
2666 * returning \\server\share\ .
2668 if (base == file_name + 1 &&
2669 g_ascii_isalpha (file_name[0]) &&
2670 file_name[1] == ':')
2672 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2673 G_IS_DIR_SEPARATOR (file_name[1]) &&
2675 !G_IS_DIR_SEPARATOR (file_name[2]) &&
2676 base >= file_name + 2)
2678 const gchar *p = file_name + 2;
2679 while (*p && !G_IS_DIR_SEPARATOR (*p))
2683 len = (guint) strlen (file_name) + 1;
2684 base = g_new (gchar, len + 1);
2685 strcpy (base, file_name);
2686 base[len-1] = G_DIR_SEPARATOR;
2690 if (G_IS_DIR_SEPARATOR (*p))
2693 while (*p && !G_IS_DIR_SEPARATOR (*p))
2701 len = (guint) 1 + base - file_name;
2702 base = g_new (gchar, len + 1);
2703 memmove (base, file_name, len);
2710 * g_canonicalize_filename:
2711 * @filename: (type filename): the name of the file
2712 * @relative_to: (type filename) (nullable): the relative directory, or %NULL
2713 * to use the current working directory
2715 * Gets the canonical file name from @filename. All triple slashes are turned into
2716 * single slashes, and all `..` and `.`s resolved against @relative_to.
2718 * Symlinks are not followed, and the returned path is guaranteed to be absolute.
2720 * If @filename is an absolute path, @relative_to is ignored. Otherwise,
2721 * @relative_to will be prepended to @filename to make it absolute. @relative_to
2722 * must be an absolute path, or %NULL. If @relative_to is %NULL, it'll fallback
2723 * to g_get_current_dir().
2725 * This function never fails, and will canonicalize file paths even if they don't
2728 * No file system I/O is done.
2730 * Returns: (type filename) (transfer full): a newly allocated string with the
2731 * canonical file path
2735 g_canonicalize_filename (const gchar *filename,
2736 const gchar *relative_to)
2738 gchar *canon, *input, *output, *after_root, *output_start;
2740 g_return_val_if_fail (relative_to == NULL || g_path_is_absolute (relative_to), NULL);
2742 if (!g_path_is_absolute (filename))
2744 gchar *cwd_allocated = NULL;
2747 if (relative_to != NULL)
2750 cwd = cwd_allocated = g_get_current_dir ();
2752 canon = g_build_filename (cwd, filename, NULL);
2753 g_free (cwd_allocated);
2757 canon = g_strdup (filename);
2760 after_root = (char *)g_path_skip_root (canon);
2762 if (after_root == NULL)
2764 /* This shouldn't really happen, as g_get_current_dir() should
2765 return an absolute pathname, but bug 573843 shows this is
2766 not always happening */
2768 return g_build_filename (G_DIR_SEPARATOR_S, filename, NULL);
2771 /* Find the first dir separator and use the canonical dir separator. */
2772 for (output = after_root - 1;
2773 (output >= canon) && G_IS_DIR_SEPARATOR (*output);
2775 *output = G_DIR_SEPARATOR;
2777 /* 1 to re-increment after the final decrement above (so that output >= canon),
2778 * and 1 to skip the first `/`. There might not be a first `/` if
2779 * the @canon is a Windows `//server/share` style path with no
2780 * trailing directories. @after_root will be '\0' in that case. */
2782 if (*output == G_DIR_SEPARATOR)
2785 /* POSIX allows double slashes at the start to mean something special
2786 * (as does windows too). So, "//" != "/", but more than two slashes
2787 * is treated as "/".
2789 if (after_root - output == 1)
2793 output_start = output;
2796 /* input points to the next non-separator to be processed. */
2797 /* output points to the next location to write to. */
2798 g_assert (input > canon && G_IS_DIR_SEPARATOR (input[-1]));
2799 g_assert (output > canon && G_IS_DIR_SEPARATOR (output[-1]));
2800 g_assert (input >= output);
2802 /* Ignore repeated dir separators. */
2803 while (G_IS_DIR_SEPARATOR (input[0]))
2806 /* Ignore single dot directory components. */
2807 if (input[0] == '.' && (input[1] == 0 || G_IS_DIR_SEPARATOR (input[1])))
2813 /* Remove double-dot directory components along with the preceding
2814 * path component. */
2815 else if (input[0] == '.' && input[1] == '.' &&
2816 (input[2] == 0 || G_IS_DIR_SEPARATOR (input[2])))
2818 if (output > output_start)
2824 while (!G_IS_DIR_SEPARATOR (output[-1]) && output > output_start);
2830 /* Copy the input to the output until the next separator,
2831 * while converting it to canonical separator */
2834 while (*input && !G_IS_DIR_SEPARATOR (*input))
2835 *output++ = *input++;
2839 *output++ = G_DIR_SEPARATOR;
2843 /* Remove a potentially trailing dir separator */
2844 if (output > output_start && G_IS_DIR_SEPARATOR (output[-1]))
2852 #if defined(MAXPATHLEN)
2853 #define G_PATH_LENGTH MAXPATHLEN
2854 #elif defined(PATH_MAX)
2855 #define G_PATH_LENGTH PATH_MAX
2856 #elif defined(_PC_PATH_MAX)
2857 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
2859 #define G_PATH_LENGTH 2048
2863 * g_get_current_dir:
2865 * Gets the current directory.
2867 * The returned string should be freed when no longer needed.
2868 * The encoding of the returned string is system defined.
2869 * On Windows, it is always UTF-8.
2871 * Since GLib 2.40, this function will return the value of the "PWD"
2872 * environment variable if it is set and it happens to be the same as
2873 * the current directory. This can make a difference in the case that
2874 * the current directory is the target of a symbolic link.
2876 * Returns: (type filename) (transfer full): the current directory
2879 g_get_current_dir (void)
2884 wchar_t dummy[2], *wdir;
2887 len = GetCurrentDirectoryW (2, dummy);
2888 wdir = g_new (wchar_t, len);
2890 if (GetCurrentDirectoryW (len, wdir) == len - 1)
2891 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
2896 dir = g_strdup ("\\");
2902 gchar *buffer = NULL;
2904 static gulong max_len = 0;
2905 struct stat pwdbuf, dotbuf;
2907 pwd = g_getenv ("PWD");
2909 g_stat (".", &dotbuf) == 0 && g_stat (pwd, &pwdbuf) == 0 &&
2910 dotbuf.st_dev == pwdbuf.st_dev && dotbuf.st_ino == pwdbuf.st_ino)
2911 return g_strdup (pwd);
2914 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
2916 while (max_len < G_MAXULONG / 2)
2919 buffer = g_new (gchar, max_len + 1);
2921 dir = getcwd (buffer, max_len);
2923 if (dir || errno != ERANGE)
2929 if (!dir || !*buffer)
2931 /* hm, should we g_error() out here?
2932 * this can happen if e.g. "./" has mode \0000
2934 buffer[0] = G_DIR_SEPARATOR;
2938 dir = g_strdup (buffer);
2943 #endif /* !G_OS_WIN32 */
2948 /* Binary compatibility versions. Not for newly compiled code. */
2950 _GLIB_EXTERN gboolean g_file_test_utf8 (const gchar *filename,
2952 _GLIB_EXTERN gboolean g_file_get_contents_utf8 (const gchar *filename,
2956 _GLIB_EXTERN gint g_mkstemp_utf8 (gchar *tmpl);
2957 _GLIB_EXTERN gint g_file_open_tmp_utf8 (const gchar *tmpl,
2960 _GLIB_EXTERN gchar *g_get_current_dir_utf8 (void);
2964 g_file_test_utf8 (const gchar *filename,
2967 return g_file_test (filename, test);
2971 g_file_get_contents_utf8 (const gchar *filename,
2976 return g_file_get_contents (filename, contents, length, error);
2980 g_mkstemp_utf8 (gchar *tmpl)
2982 return g_mkstemp (tmpl);
2986 g_file_open_tmp_utf8 (const gchar *tmpl,
2990 return g_file_open_tmp (tmpl, name_used, error);
2994 g_get_current_dir_utf8 (void)
2996 return g_get_current_dir ();