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 * see [TOCTOU](https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use).
319 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
320 * to know whether it is safe to write to a file without being
321 * tricked into writing into a different location. It doesn't work!
323 * |[<!-- language="C" -->
325 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
327 * fd = g_open (filename, O_WRONLY);
332 * fd = g_open (filename, O_WRONLY | O_NOFOLLOW | O_CLOEXEC);
336 * if (errno == ELOOP)
337 * // file is a symlink and can be ignored
339 * // handle errors as before
347 * Another thing to note is that %G_FILE_TEST_EXISTS and
348 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
349 * system call. This usually doesn't matter, but if your program
350 * is setuid or setgid it means that these tests will give you
351 * the answer for the real user ID and group ID, rather than the
352 * effective user ID and group ID.
354 * On Windows, there are no symlinks, so testing for
355 * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
356 * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
357 * its name indicates that it is executable, checking for well-known
358 * extensions and those listed in the `PATHEXT` environment variable.
360 * Returns: whether a test was %TRUE
363 g_file_test (const gchar *filename,
371 g_return_val_if_fail (filename != NULL, FALSE);
374 /* stuff missing in std vc6 api */
375 # ifndef INVALID_FILE_ATTRIBUTES
376 # define INVALID_FILE_ATTRIBUTES -1
378 # ifndef FILE_ATTRIBUTE_DEVICE
379 # define FILE_ATTRIBUTE_DEVICE 64
381 wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
383 if (wfilename == NULL)
386 attributes = GetFileAttributesW (wfilename);
390 if (attributes == INVALID_FILE_ATTRIBUTES)
393 if (test & G_FILE_TEST_EXISTS)
396 if (test & G_FILE_TEST_IS_REGULAR)
398 if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0)
402 if (test & G_FILE_TEST_IS_DIR)
404 if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
408 /* "while" so that we can exit this "loop" with a simple "break" */
409 while (test & G_FILE_TEST_IS_EXECUTABLE)
411 const gchar *lastdot = strrchr (filename, '.');
412 const gchar *pathext = NULL, *p;
418 if (_stricmp (lastdot, ".exe") == 0 ||
419 _stricmp (lastdot, ".cmd") == 0 ||
420 _stricmp (lastdot, ".bat") == 0 ||
421 _stricmp (lastdot, ".com") == 0)
424 /* Check if it is one of the types listed in %PATHEXT% */
426 pathext = g_getenv ("PATHEXT");
430 pathext = g_utf8_casefold (pathext, -1);
432 lastdot = g_utf8_casefold (lastdot, -1);
433 extlen = strlen (lastdot);
438 const gchar *q = strchr (p, ';');
441 if (extlen == q - p &&
442 memcmp (lastdot, p, extlen) == 0)
444 g_free ((gchar *) pathext);
445 g_free ((gchar *) lastdot);
454 g_free ((gchar *) pathext);
455 g_free ((gchar *) lastdot);
461 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
464 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
469 /* For root, on some POSIX systems, access (filename, X_OK)
470 * will succeed even if no executable bits are set on the
471 * file. We fall through to a stat test to avoid that.
475 test &= ~G_FILE_TEST_IS_EXECUTABLE;
477 if (test & G_FILE_TEST_IS_SYMLINK)
481 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
485 if (test & (G_FILE_TEST_IS_REGULAR |
487 G_FILE_TEST_IS_EXECUTABLE))
491 if (stat (filename, &s) == 0)
493 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
496 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
499 /* The extra test for root when access (file, X_OK) succeeds.
501 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
502 ((s.st_mode & S_IXOTH) ||
503 (s.st_mode & S_IXUSR) ||
504 (s.st_mode & S_IXGRP)))
513 G_DEFINE_QUARK (g-file-error-quark, g_file_error)
516 * g_file_error_from_errno:
517 * @err_no: an "errno" value
519 * Gets a #GFileError constant based on the passed-in @err_no.
521 * For example, if you pass in `EEXIST` this function returns
522 * %G_FILE_ERROR_EXIST. Unlike `errno` values, you can portably
523 * assume that all #GFileError values will exist.
525 * Normally a #GFileError value goes into a #GError returned
526 * from a function that manipulates files. So you would use
527 * g_file_error_from_errno() when constructing a #GError.
529 * Returns: #GFileError corresponding to the given @err_no
532 g_file_error_from_errno (gint err_no)
538 return G_FILE_ERROR_EXIST;
543 return G_FILE_ERROR_ISDIR;
548 return G_FILE_ERROR_ACCES;
553 return G_FILE_ERROR_NAMETOOLONG;
558 return G_FILE_ERROR_NOENT;
563 return G_FILE_ERROR_NOTDIR;
568 return G_FILE_ERROR_NXIO;
573 return G_FILE_ERROR_NODEV;
578 return G_FILE_ERROR_ROFS;
583 return G_FILE_ERROR_TXTBSY;
588 return G_FILE_ERROR_FAULT;
593 return G_FILE_ERROR_LOOP;
598 return G_FILE_ERROR_NOSPC;
603 return G_FILE_ERROR_NOMEM;
608 return G_FILE_ERROR_MFILE;
613 return G_FILE_ERROR_NFILE;
618 return G_FILE_ERROR_BADF;
623 return G_FILE_ERROR_INVAL;
628 return G_FILE_ERROR_PIPE;
633 return G_FILE_ERROR_AGAIN;
638 return G_FILE_ERROR_INTR;
643 return G_FILE_ERROR_IO;
648 return G_FILE_ERROR_PERM;
653 return G_FILE_ERROR_NOSYS;
657 return G_FILE_ERROR_FAILED;
662 format_error_message (const gchar *filename,
663 const gchar *format_string,
664 int saved_errno) G_GNUC_FORMAT(2);
666 #pragma GCC diagnostic push
667 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
670 format_error_message (const gchar *filename,
671 const gchar *format_string,
677 display_name = g_filename_display_name (filename);
678 msg = g_strdup_printf (format_string, display_name, g_strerror (saved_errno));
679 g_free (display_name);
684 #pragma GCC diagnostic pop
686 /* format string must have two '%s':
688 * - the place for the filename
689 * - the place for the strerror
692 set_file_error (GError **error,
693 const gchar *filename,
694 const gchar *format_string,
697 char *msg = format_error_message (filename, format_string, saved_errno);
699 g_set_error_literal (error, G_FILE_ERROR, g_file_error_from_errno (saved_errno),
705 get_contents_stdio (const gchar *filename,
712 gsize bytes; /* always <= sizeof(buf) */
714 gsize total_bytes = 0;
715 gsize total_allocated = 0;
717 gchar *display_filename;
719 g_assert (f != NULL);
725 bytes = fread (buf, 1, sizeof (buf), f);
728 if (total_bytes > G_MAXSIZE - bytes)
731 /* Possibility of overflow eliminated above. */
732 while (total_bytes + bytes >= total_allocated)
736 if (total_allocated > G_MAXSIZE / 2)
738 total_allocated *= 2;
742 total_allocated = MIN (bytes + 1, sizeof (buf));
745 tmp = g_try_realloc (str, total_allocated);
749 display_filename = g_filename_display_name (filename);
753 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),
754 (gulong) total_allocated,
756 g_free (display_filename);
766 display_filename = g_filename_display_name (filename);
769 g_file_error_from_errno (save_errno),
770 _("Error reading file “%s”: %s"),
772 g_strerror (save_errno));
773 g_free (display_filename);
778 g_assert (str != NULL);
779 memcpy (str + total_bytes, buf, bytes);
781 total_bytes += bytes;
786 if (total_allocated == 0)
788 str = g_new (gchar, 1);
792 str[total_bytes] = '\0';
795 *length = total_bytes;
802 display_filename = g_filename_display_name (filename);
806 _("File “%s” is too large"),
808 g_free (display_filename);
821 get_contents_regfile (const gchar *filename,
822 struct stat *stat_buf,
832 gchar *display_filename;
834 size = stat_buf->st_size;
836 alloc_size = size + 1;
837 buf = g_try_malloc (alloc_size);
841 display_filename = g_filename_display_name (filename);
845 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),
848 g_free (display_filename);
853 while (bytes_read < size)
857 rc = read (fd, buf + bytes_read, size - bytes_read);
863 int save_errno = errno;
866 display_filename = g_filename_display_name (filename);
869 g_file_error_from_errno (save_errno),
870 _("Failed to read from file “%s”: %s"),
872 g_strerror (save_errno));
873 g_free (display_filename);
883 buf[bytes_read] = '\0';
886 *length = bytes_read;
902 get_contents_posix (const gchar *filename,
907 struct stat stat_buf;
910 /* O_BINARY useful on Cygwin */
911 fd = open (filename, O_RDONLY | O_BINARY | O_CLOEXEC);
915 int saved_errno = errno;
918 set_file_error (error,
920 _("Failed to open file “%s”: %s"),
926 /* I don't think this will ever fail, aside from ENOMEM, but. */
927 if (fstat (fd, &stat_buf) < 0)
929 int saved_errno = errno;
931 set_file_error (error,
933 _("Failed to get attributes of file “%s”: fstat() failed: %s"),
940 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
942 gboolean retval = get_contents_regfile (filename,
956 f = fdopen (fd, "r");
960 int saved_errno = errno;
962 set_file_error (error,
964 _("Failed to open file “%s”: fdopen() failed: %s"),
970 retval = get_contents_stdio (filename, f, contents, length, error);
976 #else /* G_OS_WIN32 */
979 get_contents_win32 (const gchar *filename,
987 f = g_fopen (filename, "rb");
991 int saved_errno = errno;
993 set_file_error (error,
995 _("Failed to open file “%s”: %s"),
1001 retval = get_contents_stdio (filename, f, contents, length, error);
1009 * g_file_get_contents:
1010 * @filename: (type filename): name of a file to read contents from, in the GLib file name encoding
1011 * @contents: (out) (array length=length) (element-type guint8): location to store an allocated string, use g_free() to free
1012 * the returned string
1013 * @length: (nullable): location to store length in bytes of the contents, or %NULL
1014 * @error: return location for a #GError, or %NULL
1016 * Reads an entire file into allocated memory, with good error
1019 * If the call was successful, it returns %TRUE and sets @contents to the file
1020 * contents and @length to the length of the file contents in bytes. The string
1021 * stored in @contents will be nul-terminated, so for text files you can pass
1022 * %NULL for the @length argument. If the call was not successful, it returns
1023 * %FALSE and sets @error. The error domain is %G_FILE_ERROR. Possible error
1024 * codes are those in the #GFileError enumeration. In the error case,
1025 * @contents is set to %NULL and @length is set to zero.
1027 * Returns: %TRUE on success, %FALSE if an error occurred
1030 g_file_get_contents (const gchar *filename,
1035 g_return_val_if_fail (filename != NULL, FALSE);
1036 g_return_val_if_fail (contents != NULL, FALSE);
1043 return get_contents_win32 (filename, contents, length, error);
1045 return get_contents_posix (filename, contents, length, error);
1050 rename_file (const char *old_name,
1051 const char *new_name,
1056 if (g_rename (old_name, new_name) == -1)
1058 int save_errno = errno;
1059 gchar *display_old_name = g_filename_display_name (old_name);
1060 gchar *display_new_name = g_filename_display_name (new_name);
1064 g_file_error_from_errno (save_errno),
1065 _("Failed to rename file “%s” to “%s”: g_rename() failed: %s"),
1068 g_strerror (save_errno));
1070 g_free (display_old_name);
1071 g_free (display_new_name);
1076 /* In order to guarantee that the *new* contents of the file are seen in
1077 * future, fsync() the directory containing the file. Otherwise if the file
1078 * system was unmounted cleanly now, it would be undefined whether the old
1079 * or new contents of the file were visible after recovery.
1081 * This assumes the @old_name and @new_name are in the same directory. */
1085 gchar *dir = g_path_get_dirname (new_name);
1086 int dir_fd = g_open (dir, O_RDONLY | O_CLOEXEC, 0);
1091 g_close (dir_fd, NULL);
1096 #endif /* HAVE_FSYNC */
1102 fd_should_be_fsynced (int fd,
1103 const gchar *test_file,
1104 GFileSetContentsFlags flags)
1107 struct stat statbuf;
1109 /* If the final destination exists and is > 0 bytes, we want to sync the
1110 * newly written file to ensure the data is on disk when we rename over
1111 * the destination. Otherwise if we get a system crash we can lose both
1112 * the new and the old file on some filesystems. (I.E. those that don't
1113 * guarantee the data is written to the disk before the metadata.)
1115 * There is no difference (in file system terms) if the old file doesn’t
1116 * already exist, apart from the fact that if the system crashes and the new
1117 * data hasn’t been fsync()ed, there is only one bit of old data to lose (that
1118 * the file didn’t exist in the first place). In some situations, such as
1119 * trashing files, the old file never exists, so it seems reasonable to avoid
1120 * the fsync(). This is not a widely applicable optimisation though.
1122 if ((flags & (G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_DURABLE)) &&
1123 (flags & G_FILE_SET_CONTENTS_ONLY_EXISTING))
1126 if (g_lstat (test_file, &statbuf) == 0)
1127 return (statbuf.st_size > 0);
1128 else if (errno == ENOENT)
1131 return TRUE; /* lstat() failed; be cautious */
1135 return (flags & (G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_DURABLE));
1137 #else /* if !HAVE_FSYNC */
1139 #endif /* !HAVE_FSYNC */
1143 truncate_file (int fd,
1145 const char *dest_file,
1150 g_win32_ftruncate (fd, length) < 0
1152 ftruncate (fd, length) < 0
1156 int saved_errno = errno;
1158 if (saved_errno == EINTR)
1162 set_file_error (error,
1164 "Failed to write file “%s”: ftruncate() failed: %s",
1172 /* closes @fd once it’s finished (on success or error) */
1174 write_to_file (const gchar *contents,
1177 const gchar *dest_file,
1181 #ifdef HAVE_FALLOCATE
1184 /* We do this on a 'best effort' basis... It may not be supported
1185 * on the underlying filesystem.
1187 (void) fallocate (fd, 0, 0, length);
1195 /* 'write' on windows uses int types, so limit count to G_MAXINT */
1196 s = write (fd, contents, MIN (length, (gsize) G_MAXINT));
1198 /* Limit count to G_MAXSSIZE to fit into the return value. */
1199 s = write (fd, contents, MIN (length, (gsize) G_MAXSSIZE));
1203 int saved_errno = errno;
1204 if (saved_errno == EINTR)
1208 set_file_error (err,
1209 dest_file, _("Failed to write file “%s”: write() failed: %s"),
1216 g_assert ((gsize) s <= length);
1225 if (do_fsync && g_fsync (fd) != 0)
1227 int saved_errno = errno;
1229 set_file_error (err,
1230 dest_file, _("Failed to write file “%s”: fsync() failed: %s"),
1239 if (!g_close (fd, err))
1246 * g_file_set_contents:
1247 * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1249 * @contents: (array length=length) (element-type guint8): string to write to the file
1250 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1251 * @error: return location for a #GError, or %NULL
1253 * Writes all of @contents to a file named @filename. This is a convenience
1254 * wrapper around calling g_file_set_contents_full() with `flags` set to
1255 * `G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING` and
1256 * `mode` set to `0666`.
1258 * Returns: %TRUE on success, %FALSE if an error occurred
1263 g_file_set_contents (const gchar *filename,
1264 const gchar *contents,
1268 return g_file_set_contents_full (filename, contents, length,
1269 G_FILE_SET_CONTENTS_CONSISTENT |
1270 G_FILE_SET_CONTENTS_ONLY_EXISTING,
1275 * g_file_set_contents_full:
1276 * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1278 * @contents: (array length=length) (element-type guint8): string to write to the file
1279 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1280 * @flags: flags controlling the safety vs speed of the operation
1281 * @mode: file mode, as passed to `open()`; typically this will be `0666`
1282 * @error: return location for a #GError, or %NULL
1284 * Writes all of @contents to a file named @filename, with good error checking.
1285 * If a file called @filename already exists it will be overwritten.
1287 * @flags control the properties of the write operation: whether it’s atomic,
1288 * and what the tradeoff is between returning quickly or being resilient to
1291 * As this function performs file I/O, it is recommended to not call it anywhere
1292 * where blocking would cause problems, such as in the main loop of a graphical
1293 * application. In particular, if @flags has any value other than
1294 * %G_FILE_SET_CONTENTS_NONE then this function may call `fsync()`.
1296 * If %G_FILE_SET_CONTENTS_CONSISTENT is set in @flags, the operation is atomic
1297 * in the sense that it is first written to a temporary file which is then
1298 * renamed to the final name.
1302 * - On UNIX, if @filename already exists hard links to @filename will break.
1303 * Also since the file is recreated, existing permissions, access control
1304 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1305 * the link itself will be replaced, not the linked file.
1307 * - On UNIX, if @filename already exists and is non-empty, and if the system
1308 * supports it (via a journalling filesystem or equivalent), and if
1309 * %G_FILE_SET_CONTENTS_CONSISTENT is set in @flags, the `fsync()` call (or
1310 * equivalent) will be used to ensure atomic replacement: @filename
1311 * will contain either its old contents or @contents, even in the face of
1312 * system power loss, the disk being unsafely removed, etc.
1314 * - On UNIX, if @filename does not already exist or is empty, there is a
1315 * possibility that system power loss etc. after calling this function will
1316 * leave @filename empty or full of NUL bytes, depending on the underlying
1317 * filesystem, unless %G_FILE_SET_CONTENTS_DURABLE and
1318 * %G_FILE_SET_CONTENTS_CONSISTENT are set in @flags.
1320 * - On Windows renaming a file will not remove an existing file with the
1321 * new name, so on Windows there is a race condition between the existing
1322 * file being removed and the temporary file being renamed.
1324 * - On Windows there is no way to remove a file that is open to some
1325 * process, or mapped into memory. Thus, this function will fail if
1326 * @filename already exists and is open.
1328 * If the call was successful, it returns %TRUE. If the call was not successful,
1329 * it returns %FALSE and sets @error. The error domain is %G_FILE_ERROR.
1330 * Possible error codes are those in the #GFileError enumeration.
1332 * Note that the name for the temporary file is constructed by appending up
1333 * to 7 characters to @filename.
1335 * If the file didn’t exist before and is created, it will be given the
1336 * permissions from @mode. Otherwise, the permissions of the existing file may
1337 * be changed to @mode depending on @flags, or they may remain unchanged.
1339 * Returns: %TRUE on success, %FALSE if an error occurred
1344 g_file_set_contents_full (const gchar *filename,
1345 const gchar *contents,
1347 GFileSetContentsFlags flags,
1351 g_return_val_if_fail (filename != NULL, FALSE);
1352 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1353 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1354 g_return_val_if_fail (length >= -1, FALSE);
1356 /* @flags are handled as follows:
1357 * - %G_FILE_SET_CONTENTS_NONE: write directly to @filename, no fsync()s
1358 * - %G_FILE_SET_CONTENTS_CONSISTENT: write to temp file, fsync() it, rename()
1359 * - %G_FILE_SET_CONTENTS_CONSISTENT | ONLY_EXISTING: as above, but skip the
1360 * fsync() if @filename doesn’t exist or is empty
1361 * - %G_FILE_SET_CONTENTS_DURABLE: write directly to @filename, fsync() it
1362 * - %G_FILE_SET_CONTENTS_DURABLE | ONLY_EXISTING: as above, but skip the
1363 * fsync() if @filename doesn’t exist or is empty
1364 * - %G_FILE_SET_CONTENTS_CONSISTENT | DURABLE: write to temp file, fsync()
1365 * it, rename(), fsync() containing directory
1366 * - %G_FILE_SET_CONTENTS_CONSISTENT | DURABLE | ONLY_EXISTING: as above, but
1367 * skip both fsync()s if @filename doesn’t exist or is empty
1371 length = strlen (contents);
1373 if (flags & G_FILE_SET_CONTENTS_CONSISTENT)
1375 gchar *tmp_filename = NULL;
1376 GError *rename_error = NULL;
1381 tmp_filename = g_strdup_printf ("%s.XXXXXX", filename);
1384 fd = g_mkstemp_full (tmp_filename, O_RDWR | O_BINARY | O_CLOEXEC, mode);
1388 int saved_errno = errno;
1390 set_file_error (error,
1391 tmp_filename, _("Failed to create file “%s”: %s"),
1394 goto consistent_out;
1397 do_fsync = fd_should_be_fsynced (fd, filename, flags);
1398 if (!write_to_file (contents, length, g_steal_fd (&fd), tmp_filename, do_fsync, error))
1400 g_unlink (tmp_filename);
1402 goto consistent_out;
1405 if (!rename_file (tmp_filename, filename, do_fsync, &rename_error))
1409 g_unlink (tmp_filename);
1410 g_propagate_error (error, rename_error);
1412 goto consistent_out;
1414 #else /* G_OS_WIN32 */
1416 /* Renaming failed, but on Windows this may just mean
1417 * the file already exists. So if the target file
1418 * exists, try deleting it and do the rename again.
1420 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1422 g_unlink (tmp_filename);
1423 g_propagate_error (error, rename_error);
1425 goto consistent_out;
1428 g_error_free (rename_error);
1430 if (g_unlink (filename) == -1)
1432 int saved_errno = errno;
1434 set_file_error (error,
1436 _("Existing file “%s” could not be removed: g_unlink() failed: %s"),
1438 g_unlink (tmp_filename);
1440 goto consistent_out;
1443 if (!rename_file (tmp_filename, filename, flags, error))
1445 g_unlink (tmp_filename);
1447 goto consistent_out;
1450 #endif /* G_OS_WIN32 */
1456 g_free (tmp_filename);
1465 open_flags = O_RDWR | O_BINARY | O_CREAT | O_CLOEXEC;
1467 /* Windows doesn’t have symlinks, so O_NOFOLLOW is unnecessary there. */
1468 open_flags |= O_NOFOLLOW;
1472 direct_fd = g_open (filename, open_flags, mode);
1476 int saved_errno = errno;
1479 /* ELOOP indicates that @filename is a symlink, since we used
1480 * O_NOFOLLOW (alternately it could indicate that @filename contains
1481 * looping or too many symlinks). In either case, try again on the
1482 * %G_FILE_SET_CONTENTS_CONSISTENT code path.
1484 * FreeBSD uses EMLINK instead of ELOOP
1485 * (https://www.freebsd.org/cgi/man.cgi?query=open&sektion=2#STANDARDS),
1486 * and NetBSD uses EFTYPE
1487 * (https://netbsd.gw.com/cgi-bin/man-cgi?open+2+NetBSD-current). */
1488 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
1489 if (saved_errno == EMLINK)
1490 #elif defined(__NetBSD__)
1491 if (saved_errno == EFTYPE)
1493 if (saved_errno == ELOOP)
1495 return g_file_set_contents_full (filename, contents, length,
1496 flags | G_FILE_SET_CONTENTS_CONSISTENT,
1498 #endif /* O_NOFOLLOW */
1501 set_file_error (error,
1502 filename, _("Failed to open file “%s”: %s"),
1507 do_fsync = fd_should_be_fsynced (direct_fd, filename, flags);
1508 if (!truncate_file (direct_fd, 0, filename, error))
1510 if (!write_to_file (contents, length, g_steal_fd (&direct_fd), filename,
1519 * get_tmp_file based on the mkstemp implementation from the GNU C library.
1520 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1522 typedef gint (*GTmpFileCallback) (const gchar *, gint, gint);
1525 get_tmp_file (gchar *tmpl,
1532 static const char letters[] =
1533 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1534 static const int NLETTERS = sizeof (letters) - 1;
1537 static int counter = 0;
1539 g_return_val_if_fail (tmpl != NULL, -1);
1541 /* find the last occurrence of "XXXXXX" */
1542 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1544 if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1550 /* Get some more or less random data. */
1551 now_us = g_get_real_time ();
1552 value = ((now_us % G_USEC_PER_SEC) ^ (now_us / G_USEC_PER_SEC)) + counter++;
1554 for (count = 0; count < 100; value += 7777, ++count)
1558 /* Fill in the random bits. */
1559 XXXXXX[0] = letters[v % NLETTERS];
1561 XXXXXX[1] = letters[v % NLETTERS];
1563 XXXXXX[2] = letters[v % NLETTERS];
1565 XXXXXX[3] = letters[v % NLETTERS];
1567 XXXXXX[4] = letters[v % NLETTERS];
1569 XXXXXX[5] = letters[v % NLETTERS];
1571 fd = f (tmpl, flags, mode);
1575 else if (errno != EEXIST)
1576 /* Any other error will apply also to other names we might
1577 * try, and there are 2^32 or so of them, so give up now.
1582 /* We got out of the loop because we ran out of combinations to try. */
1587 /* Some GTmpFileCallback implementations.
1589 * Note: we cannot use open() or g_open() directly because even though
1590 * they appear compatible, they may be vararg functions and calling
1591 * varargs functions through a non-varargs type is undefined.
1594 wrap_g_mkdir (const gchar *filename,
1595 int flags G_GNUC_UNUSED,
1598 /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1599 return g_mkdir (filename, mode);
1603 wrap_g_open (const gchar *filename,
1607 return g_open (filename, flags, mode);
1611 * g_mkdtemp_full: (skip)
1612 * @tmpl: (type filename): template directory name
1613 * @mode: permissions to create the temporary directory with
1615 * Creates a temporary directory. See the mkdtemp() documentation
1616 * on most UNIX-like systems.
1618 * The parameter is a string that should follow the rules for
1619 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1620 * g_mkdtemp_full() is slightly more flexible than mkdtemp() in that the
1621 * sequence does not have to occur at the very end of the template
1622 * and you can pass a @mode. The X string will be modified to form
1623 * the name of a directory that didn't exist. The string should be
1624 * in the GLib file name encoding. Most importantly, on Windows it
1625 * should be in UTF-8.
1627 * If you are going to be creating a temporary directory inside the
1628 * directory returned by g_get_tmp_dir(), you might want to use
1629 * g_dir_make_tmp() instead.
1631 * Returns: (nullable) (type filename): A pointer to @tmpl, which has been
1632 * modified to hold the directory name. In case of errors, %NULL is
1633 * returned, and %errno will be set.
1638 g_mkdtemp_full (gchar *tmpl,
1641 if (get_tmp_file (tmpl, wrap_g_mkdir, 0, mode) == -1)
1649 * @tmpl: (type filename): template directory name
1651 * Creates a temporary directory. See the mkdtemp() documentation
1652 * on most UNIX-like systems.
1654 * The parameter is a string that should follow the rules for
1655 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1656 * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1657 * sequence does not have to occur at the very end of the template.
1658 * The X string will be modified to form the name of a directory that
1660 * The string should be in the GLib file name encoding. Most importantly,
1661 * on Windows it should be in UTF-8.
1663 * If you are going to be creating a temporary directory inside the
1664 * directory returned by g_get_tmp_dir(), you might want to use
1665 * g_dir_make_tmp() instead.
1667 * Returns: (nullable) (type filename): A pointer to @tmpl, which has been
1668 * modified to hold the directory name. In case of errors, %NULL is
1669 * returned and %errno will be set.
1674 g_mkdtemp (gchar *tmpl)
1676 return g_mkdtemp_full (tmpl, 0700);
1680 * g_mkstemp_full: (skip)
1681 * @tmpl: (type filename): template filename
1682 * @flags: flags to pass to an open() call in addition to O_EXCL
1683 * and O_CREAT, which are passed automatically
1684 * @mode: permissions to create the temporary file with
1686 * Opens a temporary file. See the mkstemp() documentation
1687 * on most UNIX-like systems.
1689 * The parameter is a string that should follow the rules for
1690 * mkstemp() templates, i.e. contain the string "XXXXXX".
1691 * g_mkstemp_full() is slightly more flexible than mkstemp()
1692 * in that the sequence does not have to occur at the very end of the
1693 * template and you can pass a @mode and additional @flags. The X
1694 * string will be modified to form the name of a file that didn't exist.
1695 * The string should be in the GLib file name encoding. Most importantly,
1696 * on Windows it should be in UTF-8.
1698 * Returns: A file handle (as from open()) to the file
1699 * opened for reading and writing. The file handle should be
1700 * closed with close(). In case of errors, -1 is returned
1701 * and %errno will be set.
1706 g_mkstemp_full (gchar *tmpl,
1710 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1711 return get_tmp_file (tmpl, wrap_g_open,
1712 flags | O_CREAT | O_EXCL, mode);
1717 * @tmpl: (type filename): template filename
1719 * Opens a temporary file. See the mkstemp() documentation
1720 * on most UNIX-like systems.
1722 * The parameter is a string that should follow the rules for
1723 * mkstemp() templates, i.e. contain the string "XXXXXX".
1724 * g_mkstemp() is slightly more flexible than mkstemp() in that the
1725 * sequence does not have to occur at the very end of the template.
1726 * The X string will be modified to form the name of a file that
1727 * didn't exist. The string should be in the GLib file name encoding.
1728 * Most importantly, on Windows it should be in UTF-8.
1730 * Returns: A file handle (as from open()) to the file
1731 * opened for reading and writing. The file is opened in binary
1732 * mode on platforms where there is a difference. The file handle
1733 * should be closed with close(). In case of errors, -1 is
1734 * returned and %errno will be set.
1737 g_mkstemp (gchar *tmpl)
1739 return g_mkstemp_full (tmpl, O_RDWR | O_BINARY | O_CLOEXEC, 0600);
1743 g_get_tmp_name (const gchar *tmpl,
1759 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1761 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1765 gchar *display_tmpl = g_filename_display_name (tmpl);
1772 G_FILE_ERROR_FAILED,
1773 _("Template “%s” invalid, should not contain a “%s”"),
1775 g_free (display_tmpl);
1780 if (strstr (tmpl, "XXXXXX") == NULL)
1782 gchar *display_tmpl = g_filename_display_name (tmpl);
1785 G_FILE_ERROR_FAILED,
1786 _("Template “%s” doesn’t contain XXXXXX"),
1788 g_free (display_tmpl);
1792 tmpdir = g_get_tmp_dir ();
1794 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1797 sep = G_DIR_SEPARATOR_S;
1799 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1801 retval = get_tmp_file (fulltemplate, f, flags, mode);
1804 int saved_errno = errno;
1806 set_file_error (error,
1808 _("Failed to create file “%s”: %s"),
1810 g_free (fulltemplate);
1814 *name_used = fulltemplate;
1821 * @tmpl: (type filename) (nullable): Template for file name, as in
1822 * g_mkstemp(), basename only, or %NULL for a default template
1823 * @name_used: (out) (type filename): location to store actual name used,
1825 * @error: return location for a #GError
1827 * Opens a file for writing in the preferred directory for temporary
1828 * files (as returned by g_get_tmp_dir()).
1830 * @tmpl should be a string in the GLib file name encoding containing
1831 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1832 * However, unlike these functions, the template should only be a
1833 * basename, no directory components are allowed. If template is
1834 * %NULL, a default template is used.
1836 * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
1837 * modified, and might thus be a read-only literal string.
1839 * Upon success, and if @name_used is non-%NULL, the actual name used
1840 * is returned in @name_used. This string should be freed with g_free()
1841 * when not needed any longer. The returned name is in the GLib file
1844 * Returns: A file handle (as from open()) to the file opened for
1845 * reading and writing. The file is opened in binary mode on platforms
1846 * where there is a difference. The file handle should be closed with
1847 * close(). In case of errors, -1 is returned and @error will be set.
1850 g_file_open_tmp (const gchar *tmpl,
1854 gchar *fulltemplate;
1857 g_return_val_if_fail (error == NULL || *error == NULL, -1);
1859 result = g_get_tmp_name (tmpl, &fulltemplate,
1861 O_CREAT | O_EXCL | O_RDWR | O_BINARY | O_CLOEXEC,
1867 *name_used = fulltemplate;
1869 g_free (fulltemplate);
1877 * @tmpl: (type filename) (nullable): Template for directory name,
1878 * as in g_mkdtemp(), basename only, or %NULL for a default template
1879 * @error: return location for a #GError
1881 * Creates a subdirectory in the preferred directory for temporary
1882 * files (as returned by g_get_tmp_dir()).
1884 * @tmpl should be a string in the GLib file name encoding containing
1885 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1886 * However, unlike these functions, the template should only be a
1887 * basename, no directory components are allowed. If template is
1888 * %NULL, a default template is used.
1890 * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
1891 * modified, and might thus be a read-only literal string.
1893 * Returns: (type filename) (transfer full): The actual name used. This string
1894 * should be freed with g_free() when not needed any longer and is
1895 * is in the GLib file name encoding. In case of errors, %NULL is
1896 * returned and @error will be set.
1901 g_dir_make_tmp (const gchar *tmpl,
1904 gchar *fulltemplate;
1906 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1908 if (g_get_tmp_name (tmpl, &fulltemplate, wrap_g_mkdir, 0, 0700, error) == -1)
1911 return fulltemplate;
1915 g_build_path_va (const gchar *separator,
1916 const gchar *first_element,
1921 gint separator_len = strlen (separator);
1922 gboolean is_first = TRUE;
1923 gboolean have_leading = FALSE;
1924 const gchar *single_element = NULL;
1925 const gchar *next_element;
1926 const gchar *last_trailing = NULL;
1929 result = g_string_new (NULL);
1932 next_element = str_array[i++];
1934 next_element = first_element;
1938 const gchar *element;
1944 element = next_element;
1946 next_element = str_array[i++];
1948 next_element = va_arg (*args, gchar *);
1953 /* Ignore empty elements */
1961 while (strncmp (start, separator, separator_len) == 0)
1962 start += separator_len;
1965 end = start + strlen (start);
1969 while (end >= start + separator_len &&
1970 strncmp (end - separator_len, separator, separator_len) == 0)
1971 end -= separator_len;
1973 last_trailing = end;
1974 while (last_trailing >= element + separator_len &&
1975 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1976 last_trailing -= separator_len;
1980 /* If the leading and trailing separator strings are in the
1981 * same element and overlap, the result is exactly that element
1983 if (last_trailing <= start)
1984 single_element = element;
1986 g_string_append_len (result, element, start - element);
1987 have_leading = TRUE;
1990 single_element = NULL;
1997 g_string_append (result, separator);
1999 g_string_append_len (result, start, end - start);
2005 g_string_free (result, TRUE);
2006 return g_strdup (single_element);
2011 g_string_append (result, last_trailing);
2013 return g_string_free (result, FALSE);
2019 * @separator: a string used to separator the elements of the path.
2020 * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
2021 * array of strings containing the path elements.
2023 * Behaves exactly like g_build_path(), but takes the path elements
2024 * as a string array, instead of variadic arguments.
2026 * This function is mainly meant for language bindings.
2028 * Returns: (type filename) (transfer full): a newly-allocated string that
2029 * must be freed with g_free().
2034 g_build_pathv (const gchar *separator,
2040 return g_build_path_va (separator, NULL, NULL, args);
2046 * @separator: (type filename): a string used to separator the elements of the path.
2047 * @first_element: (type filename): the first element in the path
2048 * @...: remaining elements in path, terminated by %NULL
2050 * Creates a path from a series of elements using @separator as the
2051 * separator between elements.
2053 * At the boundary between two elements, any trailing occurrences of
2054 * separator in the first element, or leading occurrences of separator
2055 * in the second element are removed and exactly one copy of the
2056 * separator is inserted.
2058 * Empty elements are ignored.
2060 * The number of leading copies of the separator on the result is
2061 * the same as the number of leading copies of the separator on
2062 * the first non-empty element.
2064 * The number of trailing copies of the separator on the result is
2065 * the same as the number of trailing copies of the separator on
2066 * the last non-empty element. (Determination of the number of
2067 * trailing copies is done without stripping leading copies, so
2068 * if the separator is `ABA`, then `ABABA` has 1 trailing copy.)
2070 * However, if there is only a single non-empty element, and there
2071 * are no characters in that element not part of the leading or
2072 * trailing separators, then the result is exactly the original value
2075 * Other than for determination of the number of leading and trailing
2076 * copies of the separator, elements consisting only of copies
2077 * of the separator are ignored.
2079 * Returns: (type filename) (transfer full): the newly allocated path
2082 g_build_path (const gchar *separator,
2083 const gchar *first_element,
2089 g_return_val_if_fail (separator != NULL, NULL);
2091 va_start (args, first_element);
2092 str = g_build_path_va (separator, first_element, &args, NULL);
2101 g_build_pathname_va (const gchar *first_element,
2105 /* Code copied from g_build_pathv(), and modified to use two
2106 * alternative single-character separators.
2109 gboolean is_first = TRUE;
2110 gboolean have_leading = FALSE;
2111 const gchar *single_element = NULL;
2112 const gchar *next_element;
2113 const gchar *last_trailing = NULL;
2114 gchar current_separator = '\\';
2117 result = g_string_new (NULL);
2120 next_element = str_array[i++];
2122 next_element = first_element;
2126 const gchar *element;
2132 element = next_element;
2134 next_element = str_array[i++];
2136 next_element = va_arg (*args, gchar *);
2141 /* Ignore empty elements */
2150 (*start == '\\' || *start == '/'))
2152 current_separator = *start;
2157 end = start + strlen (start);
2161 while (end >= start + 1 &&
2162 (end[-1] == '\\' || end[-1] == '/'))
2164 current_separator = end[-1];
2168 last_trailing = end;
2169 while (last_trailing >= element + 1 &&
2170 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
2175 /* If the leading and trailing separator strings are in the
2176 * same element and overlap, the result is exactly that element
2178 if (last_trailing <= start)
2179 single_element = element;
2181 g_string_append_len (result, element, start - element);
2182 have_leading = TRUE;
2185 single_element = NULL;
2192 g_string_append_len (result, ¤t_separator, 1);
2194 g_string_append_len (result, start, end - start);
2200 g_string_free (result, TRUE);
2201 return g_strdup (single_element);
2206 g_string_append (result, last_trailing);
2208 return g_string_free (result, FALSE);
2215 g_build_filename_va (const gchar *first_argument,
2222 str = g_build_path_va (G_DIR_SEPARATOR_S, first_argument, args, str_array);
2224 str = g_build_pathname_va (first_argument, args, str_array);
2231 * g_build_filename_valist:
2232 * @first_element: (type filename): the first element in the path
2233 * @args: va_list of remaining elements in path
2235 * Creates a filename from a list of elements using the correct
2236 * separator for the current platform.
2238 * Behaves exactly like g_build_filename(), but takes the path elements
2241 * This function is mainly meant for implementing other variadic arguments
2244 * Returns: (type filename) (transfer full): the newly allocated path
2249 g_build_filename_valist (const gchar *first_element,
2252 g_return_val_if_fail (first_element != NULL, NULL);
2254 return g_build_filename_va (first_element, args, NULL);
2258 * g_build_filenamev:
2259 * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
2260 * array of strings containing the path elements.
2262 * Creates a filename from a vector of elements using the correct
2263 * separator for the current platform.
2265 * This function behaves exactly like g_build_filename(), but takes the path
2266 * elements as a string array, instead of varargs. This function is mainly
2267 * meant for language bindings.
2269 * If you are building a path programmatically you may want to use
2270 * #GPathBuf instead.
2272 * Returns: (type filename) (transfer full): the newly allocated path
2277 g_build_filenamev (gchar **args)
2279 return g_build_filename_va (NULL, NULL, args);
2284 * @first_element: (type filename): the first element in the path
2285 * @...: remaining elements in path, terminated by %NULL
2287 * Creates a filename from a series of elements using the correct
2288 * separator for the current platform.
2290 * On Unix, this function behaves identically to `g_build_path
2291 * (G_DIR_SEPARATOR_S, first_element, ....)`.
2293 * On Windows, it takes into account that either the backslash
2294 * (`\` or slash (`/`) can be used as separator in filenames, but
2295 * otherwise behaves as on UNIX. When file pathname separators need
2296 * to be inserted, the one that last previously occurred in the
2297 * parameters (reading from left to right) is used.
2299 * No attempt is made to force the resulting filename to be an absolute
2300 * path. If the first element is a relative path, the result will
2301 * be a relative path.
2303 * If you are building a path programmatically you may want to use
2304 * #GPathBuf instead.
2306 * Returns: (type filename) (transfer full): the newly allocated path
2309 g_build_filename (const gchar *first_element,
2315 va_start (args, first_element);
2316 str = g_build_filename_va (first_element, &args, NULL);
2324 * @filename: (type filename): the symbolic link
2325 * @error: return location for a #GError
2327 * Reads the contents of the symbolic link @filename like the POSIX
2328 * `readlink()` function.
2330 * The returned string is in the encoding used for filenames. Use
2331 * g_filename_to_utf8() to convert it to UTF-8.
2333 * The returned string may also be a relative path. Use g_build_filename()
2334 * to convert it to an absolute path:
2336 * |[<!-- language="C" -->
2337 * g_autoptr(GError) local_error = NULL;
2338 * g_autofree gchar *link_target = g_file_read_link ("/etc/localtime", &local_error);
2340 * if (local_error != NULL)
2341 * g_error ("Error reading link: %s", local_error->message);
2343 * if (!g_path_is_absolute (link_target))
2345 * g_autofree gchar *absolute_link_target = g_build_filename ("/etc", link_target, NULL);
2346 * g_free (link_target);
2347 * link_target = g_steal_pointer (&absolute_link_target);
2351 * Returns: (type filename) (transfer full): A newly-allocated string with
2352 * the contents of the symbolic link, or %NULL if an error occurred.
2357 g_file_read_link (const gchar *filename,
2360 #if defined (HAVE_READLINK)
2365 g_return_val_if_fail (filename != NULL, NULL);
2366 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2369 buffer = g_malloc (size);
2373 read_size = readlink (filename, buffer, size);
2376 int saved_errno = errno;
2378 set_file_error (error,
2380 _("Failed to read the symbolic link “%s”: %s"),
2386 if ((size_t) read_size < size)
2388 buffer[read_size] = 0;
2393 buffer = g_realloc (buffer, size);
2395 #elif defined (G_OS_WIN32)
2399 g_return_val_if_fail (filename != NULL, NULL);
2400 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2402 read_size = g_win32_readlink_utf8 (filename, NULL, 0, &buffer, TRUE);
2405 int saved_errno = errno;
2407 set_file_error (error,
2409 _("Failed to read the symbolic link “%s”: %s"),
2413 else if (read_size == 0)
2418 g_return_val_if_fail (filename != NULL, NULL);
2419 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2421 g_set_error_literal (error,
2424 _("Symbolic links not supported"));
2431 * g_path_is_absolute:
2432 * @file_name: (type filename): a file name
2434 * Returns %TRUE if the given @file_name is an absolute file name.
2435 * Note that this is a somewhat vague concept on Windows.
2437 * On POSIX systems, an absolute file name is well-defined. It always
2438 * starts from the single root directory. For example "/usr/local".
2440 * On Windows, the concepts of current drive and drive-specific
2441 * current directory introduce vagueness. This function interprets as
2442 * an absolute file name one that either begins with a directory
2443 * separator such as "\Users\tml" or begins with the root on a drive,
2444 * for example "C:\Windows". The first case also includes UNC paths
2445 * such as "\\\\myserver\docs\foo". In all cases, either slashes or
2446 * backslashes are accepted.
2448 * Note that a file name relative to the current drive root does not
2449 * truly specify a file uniquely over time and across processes, as
2450 * the current drive is a per-process value and can be changed.
2452 * File names relative the current directory on some specific drive,
2453 * such as "D:foo/bar", are not interpreted as absolute by this
2454 * function, but they obviously are not relative to the normal current
2455 * directory as returned by getcwd() or g_get_current_dir()
2456 * either. Such paths should be avoided, or need to be handled using
2457 * Windows-specific code.
2459 * Returns: %TRUE if @file_name is absolute
2462 g_path_is_absolute (const gchar *file_name)
2464 g_return_val_if_fail (file_name != NULL, FALSE);
2466 if (G_IS_DIR_SEPARATOR (file_name[0]))
2470 /* Recognize drive letter on native Windows */
2471 if (g_ascii_isalpha (file_name[0]) &&
2472 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
2481 * @file_name: (type filename): a file name
2483 * Returns a pointer into @file_name after the root component,
2484 * i.e. after the "/" in UNIX or "C:\" under Windows. If @file_name
2485 * is not an absolute path it returns %NULL.
2487 * Returns: (type filename) (nullable): a pointer into @file_name after the
2491 g_path_skip_root (const gchar *file_name)
2493 g_return_val_if_fail (file_name != NULL, NULL);
2495 #ifdef G_PLATFORM_WIN32
2496 /* Skip \\server\share or //server/share */
2497 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2498 G_IS_DIR_SEPARATOR (file_name[1]) &&
2500 !G_IS_DIR_SEPARATOR (file_name[2]))
2503 p = strchr (file_name + 2, G_DIR_SEPARATOR);
2509 q = strchr (file_name + 2, '/');
2510 if (p == NULL || (q != NULL && q < p))
2515 if (p && p > file_name + 2 && p[1])
2519 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
2522 /* Possibly skip a backslash after the share name */
2523 if (G_IS_DIR_SEPARATOR (file_name[0]))
2526 return (gchar *)file_name;
2531 /* Skip initial slashes */
2532 if (G_IS_DIR_SEPARATOR (file_name[0]))
2534 while (G_IS_DIR_SEPARATOR (file_name[0]))
2536 return (gchar *)file_name;
2541 if (g_ascii_isalpha (file_name[0]) &&
2542 file_name[1] == ':' &&
2543 G_IS_DIR_SEPARATOR (file_name[2]))
2544 return (gchar *)file_name + 3;
2552 * @file_name: (type filename): the name of the file
2554 * Gets the name of the file without any leading directory
2555 * components. It returns a pointer into the given file name
2558 * Returns: (type filename): the name of the file without any leading
2559 * directory components
2561 * Deprecated:2.2: Use g_path_get_basename() instead, but notice
2562 * that g_path_get_basename() allocates new memory for the
2563 * returned string, unlike this function which returns a pointer
2564 * into the argument.
2567 g_basename (const gchar *file_name)
2571 g_return_val_if_fail (file_name != NULL, NULL);
2573 base = strrchr (file_name, G_DIR_SEPARATOR);
2578 q = strrchr (file_name, '/');
2579 if (base == NULL || (q != NULL && q > base))
2588 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2589 return (gchar*) file_name + 2;
2592 return (gchar*) file_name;
2596 * g_path_get_basename:
2597 * @file_name: (type filename): the name of the file
2599 * Gets the last component of the filename.
2601 * If @file_name ends with a directory separator it gets the component
2602 * before the last slash. If @file_name consists only of directory
2603 * separators (and on Windows, possibly a drive letter), a single
2604 * separator is returned. If @file_name is empty, it gets ".".
2606 * Returns: (type filename) (transfer full): a newly allocated string
2607 * containing the last component of the filename
2610 g_path_get_basename (const gchar *file_name)
2613 gssize last_nonslash;
2617 g_return_val_if_fail (file_name != NULL, NULL);
2619 if (file_name[0] == '\0')
2620 return g_strdup (".");
2622 last_nonslash = strlen (file_name) - 1;
2624 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
2627 if (last_nonslash == -1)
2628 /* string only containing slashes */
2629 return g_strdup (G_DIR_SEPARATOR_S);
2632 if (last_nonslash == 1 &&
2633 g_ascii_isalpha (file_name[0]) &&
2634 file_name[1] == ':')
2635 /* string only containing slashes and a drive */
2636 return g_strdup (G_DIR_SEPARATOR_S);
2638 base = last_nonslash;
2640 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
2645 g_ascii_isalpha (file_name[0]) &&
2646 file_name[1] == ':')
2648 #endif /* G_OS_WIN32 */
2650 len = last_nonslash - base;
2651 retval = g_malloc (len + 1);
2652 memcpy (retval, file_name + (base + 1), len);
2653 retval [len] = '\0';
2660 * @file_name: (type filename): the name of the file
2662 * Gets the directory components of a file name.
2664 * If the file name has no directory components "." is returned.
2665 * The returned string should be freed when no longer needed.
2667 * Returns: (type filename) (transfer full): the directory components of the file
2669 * Deprecated: use g_path_get_dirname() instead
2673 * g_path_get_dirname:
2674 * @file_name: (type filename): the name of the file
2676 * Gets the directory components of a file name. For example, the directory
2677 * component of `/usr/bin/test` is `/usr/bin`. The directory component of `/`
2680 * If the file name has no directory components "." is returned.
2681 * The returned string should be freed when no longer needed.
2683 * Returns: (type filename) (transfer full): the directory components of the file
2686 g_path_get_dirname (const gchar *file_name)
2691 g_return_val_if_fail (file_name != NULL, NULL);
2693 base = strrchr (file_name, G_DIR_SEPARATOR);
2698 q = strrchr (file_name, '/');
2699 if (base == NULL || (q != NULL && q > base))
2707 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2709 gchar drive_colon_dot[4];
2711 drive_colon_dot[0] = file_name[0];
2712 drive_colon_dot[1] = ':';
2713 drive_colon_dot[2] = '.';
2714 drive_colon_dot[3] = '\0';
2716 return g_strdup (drive_colon_dot);
2719 return g_strdup (".");
2722 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
2726 /* base points to the char before the last slash.
2728 * In case file_name is the root of a drive (X:\) or a child of the
2729 * root of a drive (X:\foo), include the slash.
2731 * In case file_name is the root share of an UNC path
2732 * (\\server\share), add a slash, returning \\server\share\ .
2734 * In case file_name is a direct child of a share in an UNC path
2735 * (\\server\share\foo), include the slash after the share name,
2736 * returning \\server\share\ .
2738 if (base == file_name + 1 &&
2739 g_ascii_isalpha (file_name[0]) &&
2740 file_name[1] == ':')
2742 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2743 G_IS_DIR_SEPARATOR (file_name[1]) &&
2745 !G_IS_DIR_SEPARATOR (file_name[2]) &&
2746 base >= file_name + 2)
2748 const gchar *p = file_name + 2;
2749 while (*p && !G_IS_DIR_SEPARATOR (*p))
2753 len = (guint) strlen (file_name) + 1;
2754 base = g_new (gchar, len + 1);
2755 strcpy (base, file_name);
2756 base[len-1] = G_DIR_SEPARATOR;
2760 if (G_IS_DIR_SEPARATOR (*p))
2763 while (*p && !G_IS_DIR_SEPARATOR (*p))
2771 len = (guint) 1 + base - file_name;
2772 base = g_new (gchar, len + 1);
2773 memmove (base, file_name, len);
2780 * g_canonicalize_filename:
2781 * @filename: (type filename): the name of the file
2782 * @relative_to: (type filename) (nullable): the relative directory, or %NULL
2783 * to use the current working directory
2785 * Gets the canonical file name from @filename. All triple slashes are turned into
2786 * single slashes, and all `..` and `.`s resolved against @relative_to.
2788 * Symlinks are not followed, and the returned path is guaranteed to be absolute.
2790 * If @filename is an absolute path, @relative_to is ignored. Otherwise,
2791 * @relative_to will be prepended to @filename to make it absolute. @relative_to
2792 * must be an absolute path, or %NULL. If @relative_to is %NULL, it'll fallback
2793 * to g_get_current_dir().
2795 * This function never fails, and will canonicalize file paths even if they don't
2798 * No file system I/O is done.
2800 * Returns: (type filename) (transfer full): a newly allocated string with the
2801 * canonical file path
2806 g_canonicalize_filename (const gchar *filename,
2807 const gchar *relative_to)
2809 gchar *canon, *input, *output, *after_root, *output_start;
2811 g_return_val_if_fail (relative_to == NULL || g_path_is_absolute (relative_to), NULL);
2813 if (!g_path_is_absolute (filename))
2815 gchar *cwd_allocated = NULL;
2818 if (relative_to != NULL)
2821 cwd = cwd_allocated = g_get_current_dir ();
2823 canon = g_build_filename (cwd, filename, NULL);
2824 g_free (cwd_allocated);
2828 canon = g_strdup (filename);
2831 after_root = (char *)g_path_skip_root (canon);
2833 if (after_root == NULL)
2835 /* This shouldn't really happen, as g_get_current_dir() should
2836 return an absolute pathname, but bug 573843 shows this is
2837 not always happening */
2839 return g_build_filename (G_DIR_SEPARATOR_S, filename, NULL);
2842 /* Find the first dir separator and use the canonical dir separator. */
2843 for (output = after_root - 1;
2844 (output >= canon) && G_IS_DIR_SEPARATOR (*output);
2846 *output = G_DIR_SEPARATOR;
2848 /* 1 to re-increment after the final decrement above (so that output >= canon),
2849 * and 1 to skip the first `/`. There might not be a first `/` if
2850 * the @canon is a Windows `//server/share` style path with no
2851 * trailing directories. @after_root will be '\0' in that case. */
2853 if (*output == G_DIR_SEPARATOR)
2856 /* POSIX allows double slashes at the start to mean something special
2857 * (as does windows too). So, "//" != "/", but more than two slashes
2858 * is treated as "/".
2860 if (after_root - output == 1)
2864 output_start = output;
2867 /* input points to the next non-separator to be processed. */
2868 /* output points to the next location to write to. */
2869 g_assert (input > canon && G_IS_DIR_SEPARATOR (input[-1]));
2870 g_assert (output > canon && G_IS_DIR_SEPARATOR (output[-1]));
2871 g_assert (input >= output);
2873 /* Ignore repeated dir separators. */
2874 while (G_IS_DIR_SEPARATOR (input[0]))
2877 /* Ignore single dot directory components. */
2878 if (input[0] == '.' && (input[1] == 0 || G_IS_DIR_SEPARATOR (input[1])))
2884 /* Remove double-dot directory components along with the preceding
2885 * path component. */
2886 else if (input[0] == '.' && input[1] == '.' &&
2887 (input[2] == 0 || G_IS_DIR_SEPARATOR (input[2])))
2889 if (output > output_start)
2895 while (!G_IS_DIR_SEPARATOR (output[-1]) && output > output_start);
2901 /* Copy the input to the output until the next separator,
2902 * while converting it to canonical separator */
2905 while (*input && !G_IS_DIR_SEPARATOR (*input))
2906 *output++ = *input++;
2910 *output++ = G_DIR_SEPARATOR;
2914 /* Remove a potentially trailing dir separator */
2915 if (output > output_start && G_IS_DIR_SEPARATOR (output[-1]))
2923 #if defined(MAXPATHLEN)
2924 #define G_PATH_LENGTH MAXPATHLEN
2925 #elif defined(PATH_MAX)
2926 #define G_PATH_LENGTH PATH_MAX
2927 #elif defined(_PC_PATH_MAX)
2928 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
2930 #define G_PATH_LENGTH 2048
2934 * g_get_current_dir:
2936 * Gets the current directory.
2938 * The returned string should be freed when no longer needed.
2939 * The encoding of the returned string is system defined.
2940 * On Windows, it is always UTF-8.
2942 * Since GLib 2.40, this function will return the value of the "PWD"
2943 * environment variable if it is set and it happens to be the same as
2944 * the current directory. This can make a difference in the case that
2945 * the current directory is the target of a symbolic link.
2947 * Returns: (type filename) (transfer full): the current directory
2950 g_get_current_dir (void)
2955 wchar_t dummy[2], *wdir;
2958 len = GetCurrentDirectoryW (2, dummy);
2959 wdir = g_new (wchar_t, len);
2961 if (GetCurrentDirectoryW (len, wdir) == len - 1)
2962 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
2967 dir = g_strdup ("\\");
2973 gchar *buffer = NULL;
2975 static gsize buffer_size = 0;
2976 struct stat pwdbuf, dotbuf;
2978 pwd = g_getenv ("PWD");
2980 g_stat (".", &dotbuf) == 0 && g_stat (pwd, &pwdbuf) == 0 &&
2981 dotbuf.st_dev == pwdbuf.st_dev && dotbuf.st_ino == pwdbuf.st_ino)
2982 return g_strdup (pwd);
2984 if (buffer_size == 0)
2985 buffer_size = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
2987 while (buffer_size < G_MAXSIZE / 2)
2990 buffer = g_new (gchar, buffer_size);
2992 dir = getcwd (buffer, buffer_size);
2994 if (dir || errno != ERANGE)
3000 /* Check that getcwd() nul-terminated the string. It should do, but the specs
3001 * don’t actually explicitly state that:
3002 * https://pubs.opengroup.org/onlinepubs/9699919799/functions/getcwd.html */
3003 g_assert (dir == NULL || strnlen (dir, buffer_size) < buffer_size);
3005 if (!dir || !*buffer)
3007 /* Fallback return value */
3008 g_assert (buffer_size >= 2);
3009 buffer[0] = G_DIR_SEPARATOR;
3013 dir = g_strdup (buffer);
3018 #endif /* !G_OS_WIN32 */
3023 /* Binary compatibility versions. Not for newly compiled code. */
3025 _GLIB_EXTERN gboolean g_file_test_utf8 (const gchar *filename,
3027 _GLIB_EXTERN gboolean g_file_get_contents_utf8 (const gchar *filename,
3031 _GLIB_EXTERN gint g_mkstemp_utf8 (gchar *tmpl);
3032 _GLIB_EXTERN gint g_file_open_tmp_utf8 (const gchar *tmpl,
3035 _GLIB_EXTERN gchar *g_get_current_dir_utf8 (void);
3039 g_file_test_utf8 (const gchar *filename,
3042 return g_file_test (filename, test);
3046 g_file_get_contents_utf8 (const gchar *filename,
3051 return g_file_get_contents (filename, contents, length, error);
3055 g_mkstemp_utf8 (gchar *tmpl)
3057 return g_mkstemp (tmpl);
3061 g_file_open_tmp_utf8 (const gchar *tmpl,
3065 return g_file_open_tmp (tmpl, name_used, error);
3069 g_get_current_dir_utf8 (void)
3071 return g_get_current_dir ();