1 /* gfileutils.c - File utility functions
3 * Copyright 2000 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public License
16 * along with this library; if not, see <http://www.gnu.org/licenses/>.
20 #include "glibconfig.h"
28 #include <sys/types.h>
39 #endif /* G_OS_WIN32 */
49 #include "gfileutils.h"
52 #include "gstdioprivate.h"
55 #ifdef HAVE_LINUX_MAGIC_H /* for btrfs check */
56 #include <linux/magic.h>
63 * @title: File Utilities
64 * @short_description: various file-related functions
66 * Do not use these APIs unless you are porting a POSIX application to Windows.
67 * A more high-level file access API is provided as GIO — see the documentation
70 * There is a group of functions which wrap the common POSIX functions
71 * dealing with filenames (g_open(), g_rename(), g_mkdir(), g_stat(),
72 * g_unlink(), g_remove(), g_fopen(), g_freopen()). The point of these
73 * wrappers is to make it possible to handle file names with any Unicode
74 * characters in them on Windows without having to use ifdefs and the
75 * wide character API in the application code.
77 * On some Unix systems, these APIs may be defined as identical to their POSIX
78 * counterparts. For this reason, you must check for and include the necessary
79 * header files (such as `fcntl.h`) before using functions like g_creat(). You
80 * must also define the relevant feature test macros.
82 * The pathname argument should be in the GLib file name encoding.
83 * On POSIX this is the actual on-disk encoding which might correspond
84 * to the locale settings of the process (or the `G_FILENAME_ENCODING`
85 * environment variable), or not.
87 * On Windows the GLib file name encoding is UTF-8. Note that the
88 * Microsoft C library does not use UTF-8, but has separate APIs for
89 * current system code page and wide characters (UTF-16). The GLib
90 * wrappers call the wide character API if present (on modern Windows
91 * systems), otherwise convert to/from the system code page.
93 * Another group of functions allows to open and read directories
94 * in the GLib file name encoding. These are g_dir_open(),
95 * g_dir_read_name(), g_dir_rewind(), g_dir_close().
100 * @G_FILE_ERROR_EXIST: Operation not permitted; only the owner of
101 * the file (or other resource) or processes with special privileges
102 * can perform the operation.
103 * @G_FILE_ERROR_ISDIR: File is a directory; you cannot open a directory
104 * for writing, or create or remove hard links to it.
105 * @G_FILE_ERROR_ACCES: Permission denied; the file permissions do not
106 * allow the attempted operation.
107 * @G_FILE_ERROR_NAMETOOLONG: Filename too long.
108 * @G_FILE_ERROR_NOENT: No such file or directory. This is a "file
109 * doesn't exist" error for ordinary files that are referenced in
110 * contexts where they are expected to already exist.
111 * @G_FILE_ERROR_NOTDIR: A file that isn't a directory was specified when
112 * a directory is required.
113 * @G_FILE_ERROR_NXIO: No such device or address. The system tried to
114 * use the device represented by a file you specified, and it
115 * couldn't find the device. This can mean that the device file was
116 * installed incorrectly, or that the physical device is missing or
117 * not correctly attached to the computer.
118 * @G_FILE_ERROR_NODEV: The underlying file system of the specified file
119 * does not support memory mapping.
120 * @G_FILE_ERROR_ROFS: The directory containing the new link can't be
121 * modified because it's on a read-only file system.
122 * @G_FILE_ERROR_TXTBSY: Text file busy.
123 * @G_FILE_ERROR_FAULT: You passed in a pointer to bad memory.
124 * (GLib won't reliably return this, don't pass in pointers to bad
126 * @G_FILE_ERROR_LOOP: Too many levels of symbolic links were encountered
127 * in looking up a file name. This often indicates a cycle of symbolic
129 * @G_FILE_ERROR_NOSPC: No space left on device; write operation on a
130 * file failed because the disk is full.
131 * @G_FILE_ERROR_NOMEM: No memory available. The system cannot allocate
132 * more virtual memory because its capacity is full.
133 * @G_FILE_ERROR_MFILE: The current process has too many files open and
134 * can't open any more. Duplicate descriptors do count toward this
136 * @G_FILE_ERROR_NFILE: There are too many distinct file openings in the
138 * @G_FILE_ERROR_BADF: Bad file descriptor; for example, I/O on a
139 * descriptor that has been closed or reading from a descriptor open
140 * only for writing (or vice versa).
141 * @G_FILE_ERROR_INVAL: Invalid argument. This is used to indicate
142 * various kinds of problems with passing the wrong argument to a
144 * @G_FILE_ERROR_PIPE: Broken pipe; there is no process reading from the
145 * other end of a pipe. Every library function that returns this
146 * error code also generates a 'SIGPIPE' signal; this signal
147 * terminates the program if not handled or blocked. Thus, your
148 * program will never actually see this code unless it has handled
149 * or blocked 'SIGPIPE'.
150 * @G_FILE_ERROR_AGAIN: Resource temporarily unavailable; the call might
151 * work if you try again later.
152 * @G_FILE_ERROR_INTR: Interrupted function call; an asynchronous signal
153 * occurred and prevented completion of the call. When this
154 * happens, you should try the call again.
155 * @G_FILE_ERROR_IO: Input/output error; usually used for physical read
156 * or write errors. i.e. the disk or other physical device hardware
157 * is returning errors.
158 * @G_FILE_ERROR_PERM: Operation not permitted; only the owner of the
159 * file (or other resource) or processes with special privileges can
160 * perform the operation.
161 * @G_FILE_ERROR_NOSYS: Function not implemented; this indicates that
162 * the system is missing some functionality.
163 * @G_FILE_ERROR_FAILED: Does not correspond to a UNIX error code; this
164 * is the standard "failed for unspecified reason" error code present
165 * in all #GError error code enumerations. Returned if no specific
168 * Values corresponding to @errno codes returned from file operations
169 * on UNIX. Unlike @errno codes, GFileError values are available on
170 * all systems, even Windows. The exact meaning of each code depends
171 * on what sort of file operation you were performing; the UNIX
172 * documentation gives more details. The following error code descriptions
173 * come from the GNU C Library manual, and are under the copyright
176 * It's not very portable to make detailed assumptions about exactly
177 * which errors will be returned from a given operation. Some errors
178 * don't occur on some systems, etc., sometimes there are subtle
179 * differences in when a system will report a given error, etc.
185 * Error domain for file operations. Errors in this domain will
186 * be from the #GFileError enumeration. See #GError for information
192 * @G_FILE_TEST_IS_REGULAR: %TRUE if the file is a regular file
193 * (not a directory). Note that this test will also return %TRUE
194 * if the tested file is a symlink to a regular file.
195 * @G_FILE_TEST_IS_SYMLINK: %TRUE if the file is a symlink.
196 * @G_FILE_TEST_IS_DIR: %TRUE if the file is a directory.
197 * @G_FILE_TEST_IS_EXECUTABLE: %TRUE if the file is executable.
198 * @G_FILE_TEST_EXISTS: %TRUE if the file exists. It may or may not
201 * A test to perform on a file using g_file_test().
205 * g_mkdir_with_parents:
206 * @pathname: (type filename): a pathname in the GLib file name encoding
207 * @mode: permissions to use for newly created directories
209 * Create a directory if it doesn't already exist. Create intermediate
210 * parent directories as needed, too.
212 * Returns: 0 if the directory already exists, or was successfully
213 * created. Returns -1 if an error occurred, with errno set.
218 g_mkdir_with_parents (const gchar
*pathname
,
223 if (pathname
== NULL
|| *pathname
== '\0')
229 fn
= g_strdup (pathname
);
231 if (g_path_is_absolute (fn
))
232 p
= (gchar
*) g_path_skip_root (fn
);
238 while (*p
&& !G_IS_DIR_SEPARATOR (*p
))
246 if (!g_file_test (fn
, G_FILE_TEST_EXISTS
))
248 if (g_mkdir (fn
, mode
) == -1 && errno
!= EEXIST
)
250 int errno_save
= errno
;
256 else if (!g_file_test (fn
, G_FILE_TEST_IS_DIR
))
264 *p
++ = G_DIR_SEPARATOR
;
265 while (*p
&& G_IS_DIR_SEPARATOR (*p
))
278 * @filename: (type filename): a filename to test in the
279 * GLib file name encoding
280 * @test: bitfield of #GFileTest flags
282 * Returns %TRUE if any of the tests in the bitfield @test are
283 * %TRUE. For example, `(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)`
284 * will return %TRUE if the file exists; the check whether it's a
285 * directory doesn't matter since the existence test is %TRUE. With
286 * the current set of available tests, there's no point passing in
287 * more than one test at a time.
289 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
290 * so for a symbolic link to a regular file g_file_test() will return
291 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
293 * Note, that for a dangling symbolic link g_file_test() will return
294 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
296 * You should never use g_file_test() to test whether it is safe
297 * to perform an operation, because there is always the possibility
298 * of the condition changing before you actually perform the operation.
299 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
300 * to know whether it is safe to write to a file without being
301 * tricked into writing into a different location. It doesn't work!
302 * |[<!-- language="C" -->
304 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
306 * fd = g_open (filename, O_WRONLY);
311 * Another thing to note is that %G_FILE_TEST_EXISTS and
312 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
313 * system call. This usually doesn't matter, but if your program
314 * is setuid or setgid it means that these tests will give you
315 * the answer for the real user ID and group ID, rather than the
316 * effective user ID and group ID.
318 * On Windows, there are no symlinks, so testing for
319 * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
320 * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
321 * its name indicates that it is executable, checking for well-known
322 * extensions and those listed in the `PATHEXT` environment variable.
324 * Returns: whether a test was %TRUE
327 g_file_test (const gchar
*filename
,
335 g_return_val_if_fail (filename
!= NULL
, FALSE
);
338 /* stuff missing in std vc6 api */
339 # ifndef INVALID_FILE_ATTRIBUTES
340 # define INVALID_FILE_ATTRIBUTES -1
342 # ifndef FILE_ATTRIBUTE_DEVICE
343 # define FILE_ATTRIBUTE_DEVICE 64
345 wfilename
= g_utf8_to_utf16 (filename
, -1, NULL
, NULL
, NULL
);
347 if (wfilename
== NULL
)
350 attributes
= GetFileAttributesW (wfilename
);
354 if (attributes
== INVALID_FILE_ATTRIBUTES
)
357 if (test
& G_FILE_TEST_EXISTS
)
360 if (test
& G_FILE_TEST_IS_REGULAR
)
362 if ((attributes
& (FILE_ATTRIBUTE_DIRECTORY
| FILE_ATTRIBUTE_DEVICE
)) == 0)
366 if (test
& G_FILE_TEST_IS_DIR
)
368 if ((attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0)
372 /* "while" so that we can exit this "loop" with a simple "break" */
373 while (test
& G_FILE_TEST_IS_EXECUTABLE
)
375 const gchar
*lastdot
= strrchr (filename
, '.');
376 const gchar
*pathext
= NULL
, *p
;
382 if (_stricmp (lastdot
, ".exe") == 0 ||
383 _stricmp (lastdot
, ".cmd") == 0 ||
384 _stricmp (lastdot
, ".bat") == 0 ||
385 _stricmp (lastdot
, ".com") == 0)
388 /* Check if it is one of the types listed in %PATHEXT% */
390 pathext
= g_getenv ("PATHEXT");
394 pathext
= g_utf8_casefold (pathext
, -1);
396 lastdot
= g_utf8_casefold (lastdot
, -1);
397 extlen
= strlen (lastdot
);
402 const gchar
*q
= strchr (p
, ';');
405 if (extlen
== q
- p
&&
406 memcmp (lastdot
, p
, extlen
) == 0)
408 g_free ((gchar
*) pathext
);
409 g_free ((gchar
*) lastdot
);
418 g_free ((gchar
*) pathext
);
419 g_free ((gchar
*) lastdot
);
425 if ((test
& G_FILE_TEST_EXISTS
) && (access (filename
, F_OK
) == 0))
428 if ((test
& G_FILE_TEST_IS_EXECUTABLE
) && (access (filename
, X_OK
) == 0))
433 /* For root, on some POSIX systems, access (filename, X_OK)
434 * will succeed even if no executable bits are set on the
435 * file. We fall through to a stat test to avoid that.
439 test
&= ~G_FILE_TEST_IS_EXECUTABLE
;
441 if (test
& G_FILE_TEST_IS_SYMLINK
)
445 if ((lstat (filename
, &s
) == 0) && S_ISLNK (s
.st_mode
))
449 if (test
& (G_FILE_TEST_IS_REGULAR
|
451 G_FILE_TEST_IS_EXECUTABLE
))
455 if (stat (filename
, &s
) == 0)
457 if ((test
& G_FILE_TEST_IS_REGULAR
) && S_ISREG (s
.st_mode
))
460 if ((test
& G_FILE_TEST_IS_DIR
) && S_ISDIR (s
.st_mode
))
463 /* The extra test for root when access (file, X_OK) succeeds.
465 if ((test
& G_FILE_TEST_IS_EXECUTABLE
) &&
466 ((s
.st_mode
& S_IXOTH
) ||
467 (s
.st_mode
& S_IXUSR
) ||
468 (s
.st_mode
& S_IXGRP
)))
477 G_DEFINE_QUARK (g
-file
-error
-quark
, g_file_error
)
480 * g_file_error_from_errno:
481 * @err_no: an "errno" value
483 * Gets a #GFileError constant based on the passed-in @err_no.
484 * For example, if you pass in `EEXIST` this function returns
485 * #G_FILE_ERROR_EXIST. Unlike `errno` values, you can portably
486 * assume that all #GFileError values will exist.
488 * Normally a #GFileError value goes into a #GError returned
489 * from a function that manipulates files. So you would use
490 * g_file_error_from_errno() when constructing a #GError.
492 * Returns: #GFileError corresponding to the given @errno
495 g_file_error_from_errno (gint err_no
)
501 return G_FILE_ERROR_EXIST
;
506 return G_FILE_ERROR_ISDIR
;
511 return G_FILE_ERROR_ACCES
;
516 return G_FILE_ERROR_NAMETOOLONG
;
521 return G_FILE_ERROR_NOENT
;
526 return G_FILE_ERROR_NOTDIR
;
531 return G_FILE_ERROR_NXIO
;
536 return G_FILE_ERROR_NODEV
;
541 return G_FILE_ERROR_ROFS
;
546 return G_FILE_ERROR_TXTBSY
;
551 return G_FILE_ERROR_FAULT
;
556 return G_FILE_ERROR_LOOP
;
561 return G_FILE_ERROR_NOSPC
;
566 return G_FILE_ERROR_NOMEM
;
571 return G_FILE_ERROR_MFILE
;
576 return G_FILE_ERROR_NFILE
;
581 return G_FILE_ERROR_BADF
;
586 return G_FILE_ERROR_INVAL
;
591 return G_FILE_ERROR_PIPE
;
596 return G_FILE_ERROR_AGAIN
;
601 return G_FILE_ERROR_INTR
;
606 return G_FILE_ERROR_IO
;
611 return G_FILE_ERROR_PERM
;
616 return G_FILE_ERROR_NOSYS
;
620 return G_FILE_ERROR_FAILED
;
625 format_error_message (const gchar
*filename
,
626 const gchar
*format_string
,
627 int saved_errno
) G_GNUC_FORMAT(2);
629 #pragma GCC diagnostic push
630 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
633 format_error_message (const gchar
*filename
,
634 const gchar
*format_string
,
640 display_name
= g_filename_display_name (filename
);
641 msg
= g_strdup_printf (format_string
, display_name
, g_strerror (saved_errno
));
642 g_free (display_name
);
647 #pragma GCC diagnostic pop
649 /* format string must have two '%s':
651 * - the place for the filename
652 * - the place for the strerror
655 set_file_error (GError
**error
,
656 const gchar
*filename
,
657 const gchar
*format_string
,
660 char *msg
= format_error_message (filename
, format_string
, saved_errno
);
662 g_set_error_literal (error
, G_FILE_ERROR
, g_file_error_from_errno (saved_errno
),
668 get_contents_stdio (const gchar
*filename
,
675 gsize bytes
; /* always <= sizeof(buf) */
677 gsize total_bytes
= 0;
678 gsize total_allocated
= 0;
680 gchar
*display_filename
;
682 g_assert (f
!= NULL
);
688 bytes
= fread (buf
, 1, sizeof (buf
), f
);
691 if (total_bytes
> G_MAXSIZE
- bytes
)
694 /* Possibility of overflow eliminated above. */
695 while (total_bytes
+ bytes
>= total_allocated
)
699 if (total_allocated
> G_MAXSIZE
/ 2)
701 total_allocated
*= 2;
705 total_allocated
= MIN (bytes
+ 1, sizeof (buf
));
708 tmp
= g_try_realloc (str
, total_allocated
);
712 display_filename
= g_filename_display_name (filename
);
716 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
),
717 (gulong
) total_allocated
,
719 g_free (display_filename
);
729 display_filename
= g_filename_display_name (filename
);
732 g_file_error_from_errno (save_errno
),
733 _("Error reading file “%s”: %s"),
735 g_strerror (save_errno
));
736 g_free (display_filename
);
741 g_assert (str
!= NULL
);
742 memcpy (str
+ total_bytes
, buf
, bytes
);
744 total_bytes
+= bytes
;
749 if (total_allocated
== 0)
751 str
= g_new (gchar
, 1);
755 str
[total_bytes
] = '\0';
758 *length
= total_bytes
;
765 display_filename
= g_filename_display_name (filename
);
769 _("File “%s” is too large"),
771 g_free (display_filename
);
784 get_contents_regfile (const gchar
*filename
,
785 struct stat
*stat_buf
,
795 gchar
*display_filename
;
797 size
= stat_buf
->st_size
;
799 alloc_size
= size
+ 1;
800 buf
= g_try_malloc (alloc_size
);
804 display_filename
= g_filename_display_name (filename
);
808 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
),
811 g_free (display_filename
);
816 while (bytes_read
< size
)
820 rc
= read (fd
, buf
+ bytes_read
, size
- bytes_read
);
826 int save_errno
= errno
;
829 display_filename
= g_filename_display_name (filename
);
832 g_file_error_from_errno (save_errno
),
833 _("Failed to read from file “%s”: %s"),
835 g_strerror (save_errno
));
836 g_free (display_filename
);
846 buf
[bytes_read
] = '\0';
849 *length
= bytes_read
;
865 get_contents_posix (const gchar
*filename
,
870 struct stat stat_buf
;
873 /* O_BINARY useful on Cygwin */
874 fd
= open (filename
, O_RDONLY
|O_BINARY
);
878 int saved_errno
= errno
;
879 set_file_error (error
,
881 _("Failed to open file “%s”: %s"),
887 /* I don't think this will ever fail, aside from ENOMEM, but. */
888 if (fstat (fd
, &stat_buf
) < 0)
890 int saved_errno
= errno
;
891 set_file_error (error
,
893 _("Failed to get attributes of file “%s”: fstat() failed: %s"),
900 if (stat_buf
.st_size
> 0 && S_ISREG (stat_buf
.st_mode
))
902 gboolean retval
= get_contents_regfile (filename
,
916 f
= fdopen (fd
, "r");
920 int saved_errno
= errno
;
921 set_file_error (error
,
923 _("Failed to open file “%s”: fdopen() failed: %s"),
929 retval
= get_contents_stdio (filename
, f
, contents
, length
, error
);
935 #else /* G_OS_WIN32 */
938 get_contents_win32 (const gchar
*filename
,
946 f
= g_fopen (filename
, "rb");
950 int saved_errno
= errno
;
951 set_file_error (error
,
953 _("Failed to open file “%s”: %s"),
959 retval
= get_contents_stdio (filename
, f
, contents
, length
, error
);
967 * g_file_get_contents:
968 * @filename: (type filename): name of a file to read contents from, in the GLib file name encoding
969 * @contents: (out) (array length=length) (element-type guint8): location to store an allocated string, use g_free() to free
970 * the returned string
971 * @length: (nullable): location to store length in bytes of the contents, or %NULL
972 * @error: return location for a #GError, or %NULL
974 * Reads an entire file into allocated memory, with good error
977 * If the call was successful, it returns %TRUE and sets @contents to the file
978 * contents and @length to the length of the file contents in bytes. The string
979 * stored in @contents will be nul-terminated, so for text files you can pass
980 * %NULL for the @length argument. If the call was not successful, it returns
981 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
982 * codes are those in the #GFileError enumeration. In the error case,
983 * @contents is set to %NULL and @length is set to zero.
985 * Returns: %TRUE on success, %FALSE if an error occurred
988 g_file_get_contents (const gchar
*filename
,
993 g_return_val_if_fail (filename
!= NULL
, FALSE
);
994 g_return_val_if_fail (contents
!= NULL
, FALSE
);
1001 return get_contents_win32 (filename
, contents
, length
, error
);
1003 return get_contents_posix (filename
, contents
, length
, error
);
1008 rename_file (const char *old_name
,
1009 const char *new_name
,
1013 if (g_rename (old_name
, new_name
) == -1)
1015 int save_errno
= errno
;
1016 gchar
*display_old_name
= g_filename_display_name (old_name
);
1017 gchar
*display_new_name
= g_filename_display_name (new_name
);
1021 g_file_error_from_errno (save_errno
),
1022 _("Failed to rename file “%s” to “%s”: g_rename() failed: %s"),
1025 g_strerror (save_errno
));
1027 g_free (display_old_name
);
1028 g_free (display_new_name
);
1037 write_to_temp_file (const gchar
*contents
,
1039 const gchar
*dest_file
,
1048 tmp_name
= g_strdup_printf ("%s.XXXXXX", dest_file
);
1051 fd
= g_mkstemp_full (tmp_name
, O_RDWR
| O_BINARY
, 0666);
1055 int saved_errno
= errno
;
1056 set_file_error (err
,
1057 tmp_name
, _("Failed to create file “%s”: %s"),
1062 #ifdef HAVE_FALLOCATE
1065 /* We do this on a 'best effort' basis... It may not be supported
1066 * on the underlying filesystem.
1068 (void) fallocate (fd
, 0, 0, length
);
1075 s
= write (fd
, contents
, length
);
1079 int saved_errno
= errno
;
1080 if (saved_errno
== EINTR
)
1083 set_file_error (err
,
1084 tmp_name
, _("Failed to write file “%s”: write() failed: %s"),
1087 g_unlink (tmp_name
);
1092 g_assert (s
<= length
);
1098 #ifdef BTRFS_SUPER_MAGIC
1102 /* On Linux, on btrfs, skip the fsync since rename-over-existing is
1103 * guaranteed to be atomic and this is the only case in which we
1104 * would fsync() anyway.
1107 if (fstatfs (fd
, &buf
) == 0 && buf
.f_type
== BTRFS_SUPER_MAGIC
)
1114 struct stat statbuf
;
1117 /* If the final destination exists and is > 0 bytes, we want to sync the
1118 * newly written file to ensure the data is on disk when we rename over
1119 * the destination. Otherwise if we get a system crash we can lose both
1120 * the new and the old file on some filesystems. (I.E. those that don't
1121 * guarantee the data is written to the disk before the metadata.)
1123 if (g_lstat (dest_file
, &statbuf
) == 0 && statbuf
.st_size
> 0 && fsync (fd
) != 0)
1125 int saved_errno
= errno
;
1126 set_file_error (err
,
1127 tmp_name
, _("Failed to write file “%s”: fsync() failed: %s"),
1130 g_unlink (tmp_name
);
1137 #ifdef BTRFS_SUPER_MAGIC
1142 if (!g_close (fd
, err
))
1144 g_unlink (tmp_name
);
1149 retval
= g_strdup (tmp_name
);
1158 * g_file_set_contents:
1159 * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1161 * @contents: (array length=length) (element-type guint8): string to write to the file
1162 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1163 * @error: return location for a #GError, or %NULL
1165 * Writes all of @contents to a file named @filename, with good error checking.
1166 * If a file called @filename already exists it will be overwritten.
1168 * This write is atomic in the sense that it is first written to a temporary
1169 * file which is then renamed to the final name. Notes:
1171 * - On UNIX, if @filename already exists hard links to @filename will break.
1172 * Also since the file is recreated, existing permissions, access control
1173 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1174 * the link itself will be replaced, not the linked file.
1176 * - On UNIX, if @filename already exists and is non-empty, and if the system
1177 * supports it (via a journalling filesystem or equivalent), the fsync()
1178 * call (or equivalent) will be used to ensure atomic replacement: @filename
1179 * will contain either its old contents or @contents, even in the face of
1180 * system power loss, the disk being unsafely removed, etc.
1182 * - On UNIX, if @filename does not already exist or is empty, there is a
1183 * possibility that system power loss etc. after calling this function will
1184 * leave @filename empty or full of NUL bytes, depending on the underlying
1187 * - On Windows renaming a file will not remove an existing file with the
1188 * new name, so on Windows there is a race condition between the existing
1189 * file being removed and the temporary file being renamed.
1191 * - On Windows there is no way to remove a file that is open to some
1192 * process, or mapped into memory. Thus, this function will fail if
1193 * @filename already exists and is open.
1195 * If the call was successful, it returns %TRUE. If the call was not successful,
1196 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1197 * Possible error codes are those in the #GFileError enumeration.
1199 * Note that the name for the temporary file is constructed by appending up
1200 * to 7 characters to @filename.
1202 * Returns: %TRUE on success, %FALSE if an error occurred
1207 g_file_set_contents (const gchar
*filename
,
1208 const gchar
*contents
,
1212 gchar
*tmp_filename
;
1214 GError
*rename_error
= NULL
;
1216 g_return_val_if_fail (filename
!= NULL
, FALSE
);
1217 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, FALSE
);
1218 g_return_val_if_fail (contents
!= NULL
|| length
== 0, FALSE
);
1219 g_return_val_if_fail (length
>= -1, FALSE
);
1222 length
= strlen (contents
);
1224 tmp_filename
= write_to_temp_file (contents
, length
, filename
, error
);
1232 if (!rename_file (tmp_filename
, filename
, &rename_error
))
1236 g_unlink (tmp_filename
);
1237 g_propagate_error (error
, rename_error
);
1241 #else /* G_OS_WIN32 */
1243 /* Renaming failed, but on Windows this may just mean
1244 * the file already exists. So if the target file
1245 * exists, try deleting it and do the rename again.
1247 if (!g_file_test (filename
, G_FILE_TEST_EXISTS
))
1249 g_unlink (tmp_filename
);
1250 g_propagate_error (error
, rename_error
);
1255 g_error_free (rename_error
);
1257 if (g_unlink (filename
) == -1)
1259 int saved_errno
= errno
;
1260 set_file_error (error
,
1262 _("Existing file “%s” could not be removed: g_unlink() failed: %s"),
1264 g_unlink (tmp_filename
);
1269 if (!rename_file (tmp_filename
, filename
, error
))
1271 g_unlink (tmp_filename
);
1282 g_free (tmp_filename
);
1287 * get_tmp_file based on the mkstemp implementation from the GNU C library.
1288 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1290 typedef gint (*GTmpFileCallback
) (const gchar
*, gint
, gint
);
1293 get_tmp_file (gchar
*tmpl
,
1300 static const char letters
[] =
1301 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1302 static const int NLETTERS
= sizeof (letters
) - 1;
1305 static int counter
= 0;
1307 g_return_val_if_fail (tmpl
!= NULL
, -1);
1309 /* find the last occurrence of "XXXXXX" */
1310 XXXXXX
= g_strrstr (tmpl
, "XXXXXX");
1312 if (!XXXXXX
|| strncmp (XXXXXX
, "XXXXXX", 6))
1318 /* Get some more or less random data. */
1319 g_get_current_time (&tv
);
1320 value
= (tv
.tv_usec
^ tv
.tv_sec
) + counter
++;
1322 for (count
= 0; count
< 100; value
+= 7777, ++count
)
1326 /* Fill in the random bits. */
1327 XXXXXX
[0] = letters
[v
% NLETTERS
];
1329 XXXXXX
[1] = letters
[v
% NLETTERS
];
1331 XXXXXX
[2] = letters
[v
% NLETTERS
];
1333 XXXXXX
[3] = letters
[v
% NLETTERS
];
1335 XXXXXX
[4] = letters
[v
% NLETTERS
];
1337 XXXXXX
[5] = letters
[v
% NLETTERS
];
1339 fd
= f (tmpl
, flags
, mode
);
1343 else if (errno
!= EEXIST
)
1344 /* Any other error will apply also to other names we might
1345 * try, and there are 2^32 or so of them, so give up now.
1350 /* We got out of the loop because we ran out of combinations to try. */
1355 /* Some GTmpFileCallback implementations.
1357 * Note: we cannot use open() or g_open() directly because even though
1358 * they appear compatible, they may be vararg functions and calling
1359 * varargs functions through a non-varargs type is undefined.
1362 wrap_g_mkdir (const gchar
*filename
,
1363 int flags G_GNUC_UNUSED
,
1366 /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1367 return g_mkdir (filename
, mode
);
1371 wrap_g_open (const gchar
*filename
,
1375 return g_open (filename
, flags
, mode
);
1379 * g_mkdtemp_full: (skip)
1380 * @tmpl: (type filename): template directory name
1381 * @mode: permissions to create the temporary directory with
1383 * Creates a temporary directory. See the mkdtemp() documentation
1384 * on most UNIX-like systems.
1386 * The parameter is a string that should follow the rules for
1387 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1388 * g_mkdtemp_full() is slightly more flexible than mkdtemp() in that the
1389 * sequence does not have to occur at the very end of the template
1390 * and you can pass a @mode. The X string will be modified to form
1391 * the name of a directory that didn't exist. The string should be
1392 * in the GLib file name encoding. Most importantly, on Windows it
1393 * should be in UTF-8.
1395 * If you are going to be creating a temporary directory inside the
1396 * directory returned by g_get_tmp_dir(), you might want to use
1397 * g_dir_make_tmp() instead.
1399 * Returns: (nullable) (type filename): A pointer to @tmpl, which has been
1400 * modified to hold the directory name. In case of errors, %NULL is
1401 * returned, and %errno will be set.
1406 g_mkdtemp_full (gchar
*tmpl
,
1409 if (get_tmp_file (tmpl
, wrap_g_mkdir
, 0, mode
) == -1)
1417 * @tmpl: (type filename): template directory name
1419 * Creates a temporary directory. See the mkdtemp() documentation
1420 * on most UNIX-like systems.
1422 * The parameter is a string that should follow the rules for
1423 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1424 * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1425 * sequence does not have to occur at the very end of the template.
1426 * The X string will be modified to form the name of a directory that
1428 * The string should be in the GLib file name encoding. Most importantly,
1429 * on Windows it should be in UTF-8.
1431 * If you are going to be creating a temporary directory inside the
1432 * directory returned by g_get_tmp_dir(), you might want to use
1433 * g_dir_make_tmp() instead.
1435 * Returns: (nullable) (type filename): A pointer to @tmpl, which has been
1436 * modified to hold the directory name. In case of errors, %NULL is
1437 * returned and %errno will be set.
1442 g_mkdtemp (gchar
*tmpl
)
1444 return g_mkdtemp_full (tmpl
, 0700);
1448 * g_mkstemp_full: (skip)
1449 * @tmpl: (type filename): template filename
1450 * @flags: flags to pass to an open() call in addition to O_EXCL
1451 * and O_CREAT, which are passed automatically
1452 * @mode: permissions to create the temporary file with
1454 * Opens a temporary file. See the mkstemp() documentation
1455 * on most UNIX-like systems.
1457 * The parameter is a string that should follow the rules for
1458 * mkstemp() templates, i.e. contain the string "XXXXXX".
1459 * g_mkstemp_full() is slightly more flexible than mkstemp()
1460 * in that the sequence does not have to occur at the very end of the
1461 * template and you can pass a @mode and additional @flags. The X
1462 * string will be modified to form the name of a file that didn't exist.
1463 * The string should be in the GLib file name encoding. Most importantly,
1464 * on Windows it should be in UTF-8.
1466 * Returns: A file handle (as from open()) to the file
1467 * opened for reading and writing. The file handle should be
1468 * closed with close(). In case of errors, -1 is returned
1469 * and %errno will be set.
1474 g_mkstemp_full (gchar
*tmpl
,
1478 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1479 return get_tmp_file (tmpl
, wrap_g_open
,
1480 flags
| O_CREAT
| O_EXCL
, mode
);
1485 * @tmpl: (type filename): template filename
1487 * Opens a temporary file. See the mkstemp() documentation
1488 * on most UNIX-like systems.
1490 * The parameter is a string that should follow the rules for
1491 * mkstemp() templates, i.e. contain the string "XXXXXX".
1492 * g_mkstemp() is slightly more flexible than mkstemp() in that the
1493 * sequence does not have to occur at the very end of the template.
1494 * The X string will be modified to form the name of a file that
1495 * didn't exist. The string should be in the GLib file name encoding.
1496 * Most importantly, on Windows it should be in UTF-8.
1498 * Returns: A file handle (as from open()) to the file
1499 * opened for reading and writing. The file is opened in binary
1500 * mode on platforms where there is a difference. The file handle
1501 * should be closed with close(). In case of errors, -1 is
1502 * returned and %errno will be set.
1505 g_mkstemp (gchar
*tmpl
)
1507 return g_mkstemp_full (tmpl
, O_RDWR
| O_BINARY
, 0600);
1511 g_get_tmp_name (const gchar
*tmpl
,
1527 if ((slash
= strchr (tmpl
, G_DIR_SEPARATOR
)) != NULL
1529 || (strchr (tmpl
, '/') != NULL
&& (slash
= "/"))
1533 gchar
*display_tmpl
= g_filename_display_name (tmpl
);
1540 G_FILE_ERROR_FAILED
,
1541 _("Template “%s” invalid, should not contain a “%s”"),
1543 g_free (display_tmpl
);
1548 if (strstr (tmpl
, "XXXXXX") == NULL
)
1550 gchar
*display_tmpl
= g_filename_display_name (tmpl
);
1553 G_FILE_ERROR_FAILED
,
1554 _("Template “%s” doesn’t contain XXXXXX"),
1556 g_free (display_tmpl
);
1560 tmpdir
= g_get_tmp_dir ();
1562 if (G_IS_DIR_SEPARATOR (tmpdir
[strlen (tmpdir
) - 1]))
1565 sep
= G_DIR_SEPARATOR_S
;
1567 fulltemplate
= g_strconcat (tmpdir
, sep
, tmpl
, NULL
);
1569 retval
= get_tmp_file (fulltemplate
, f
, flags
, mode
);
1572 int saved_errno
= errno
;
1573 set_file_error (error
,
1575 _("Failed to create file “%s”: %s"),
1577 g_free (fulltemplate
);
1581 *name_used
= fulltemplate
;
1588 * @tmpl: (type filename) (nullable): Template for file name, as in
1589 * g_mkstemp(), basename only, or %NULL for a default template
1590 * @name_used: (out) (type filename): location to store actual name used,
1592 * @error: return location for a #GError
1594 * Opens a file for writing in the preferred directory for temporary
1595 * files (as returned by g_get_tmp_dir()).
1597 * @tmpl should be a string in the GLib file name encoding containing
1598 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1599 * However, unlike these functions, the template should only be a
1600 * basename, no directory components are allowed. If template is
1601 * %NULL, a default template is used.
1603 * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
1604 * modified, and might thus be a read-only literal string.
1606 * Upon success, and if @name_used is non-%NULL, the actual name used
1607 * is returned in @name_used. This string should be freed with g_free()
1608 * when not needed any longer. The returned name is in the GLib file
1611 * Returns: A file handle (as from open()) to the file opened for
1612 * reading and writing. The file is opened in binary mode on platforms
1613 * where there is a difference. The file handle should be closed with
1614 * close(). In case of errors, -1 is returned and @error will be set.
1617 g_file_open_tmp (const gchar
*tmpl
,
1621 gchar
*fulltemplate
;
1624 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, -1);
1626 result
= g_get_tmp_name (tmpl
, &fulltemplate
,
1628 O_CREAT
| O_EXCL
| O_RDWR
| O_BINARY
,
1634 *name_used
= fulltemplate
;
1636 g_free (fulltemplate
);
1644 * @tmpl: (type filename) (nullable): Template for directory name,
1645 * as in g_mkdtemp(), basename only, or %NULL for a default template
1646 * @error: return location for a #GError
1648 * Creates a subdirectory in the preferred directory for temporary
1649 * files (as returned by g_get_tmp_dir()).
1651 * @tmpl should be a string in the GLib file name encoding containing
1652 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1653 * However, unlike these functions, the template should only be a
1654 * basename, no directory components are allowed. If template is
1655 * %NULL, a default template is used.
1657 * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
1658 * modified, and might thus be a read-only literal string.
1660 * Returns: (type filename): The actual name used. This string
1661 * should be freed with g_free() when not needed any longer and is
1662 * is in the GLib file name encoding. In case of errors, %NULL is
1663 * returned and @error will be set.
1668 g_dir_make_tmp (const gchar
*tmpl
,
1671 gchar
*fulltemplate
;
1673 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
1675 if (g_get_tmp_name (tmpl
, &fulltemplate
, wrap_g_mkdir
, 0, 0700, error
) == -1)
1678 return fulltemplate
;
1682 g_build_path_va (const gchar
*separator
,
1683 const gchar
*first_element
,
1688 gint separator_len
= strlen (separator
);
1689 gboolean is_first
= TRUE
;
1690 gboolean have_leading
= FALSE
;
1691 const gchar
*single_element
= NULL
;
1692 const gchar
*next_element
;
1693 const gchar
*last_trailing
= NULL
;
1696 result
= g_string_new (NULL
);
1699 next_element
= str_array
[i
++];
1701 next_element
= first_element
;
1705 const gchar
*element
;
1711 element
= next_element
;
1713 next_element
= str_array
[i
++];
1715 next_element
= va_arg (*args
, gchar
*);
1720 /* Ignore empty elements */
1728 while (strncmp (start
, separator
, separator_len
) == 0)
1729 start
+= separator_len
;
1732 end
= start
+ strlen (start
);
1736 while (end
>= start
+ separator_len
&&
1737 strncmp (end
- separator_len
, separator
, separator_len
) == 0)
1738 end
-= separator_len
;
1740 last_trailing
= end
;
1741 while (last_trailing
>= element
+ separator_len
&&
1742 strncmp (last_trailing
- separator_len
, separator
, separator_len
) == 0)
1743 last_trailing
-= separator_len
;
1747 /* If the leading and trailing separator strings are in the
1748 * same element and overlap, the result is exactly that element
1750 if (last_trailing
<= start
)
1751 single_element
= element
;
1753 g_string_append_len (result
, element
, start
- element
);
1754 have_leading
= TRUE
;
1757 single_element
= NULL
;
1764 g_string_append (result
, separator
);
1766 g_string_append_len (result
, start
, end
- start
);
1772 g_string_free (result
, TRUE
);
1773 return g_strdup (single_element
);
1778 g_string_append (result
, last_trailing
);
1780 return g_string_free (result
, FALSE
);
1786 * @separator: a string used to separator the elements of the path.
1787 * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
1788 * array of strings containing the path elements.
1790 * Behaves exactly like g_build_path(), but takes the path elements
1791 * as a string array, instead of varargs. This function is mainly
1792 * meant for language bindings.
1794 * Returns: (type filename): a newly-allocated string that must be freed
1800 g_build_pathv (const gchar
*separator
,
1806 return g_build_path_va (separator
, NULL
, NULL
, args
);
1812 * @separator: (type filename): a string used to separator the elements of the path.
1813 * @first_element: (type filename): the first element in the path
1814 * @...: remaining elements in path, terminated by %NULL
1816 * Creates a path from a series of elements using @separator as the
1817 * separator between elements. At the boundary between two elements,
1818 * any trailing occurrences of separator in the first element, or
1819 * leading occurrences of separator in the second element are removed
1820 * and exactly one copy of the separator is inserted.
1822 * Empty elements are ignored.
1824 * The number of leading copies of the separator on the result is
1825 * the same as the number of leading copies of the separator on
1826 * the first non-empty element.
1828 * The number of trailing copies of the separator on the result is
1829 * the same as the number of trailing copies of the separator on
1830 * the last non-empty element. (Determination of the number of
1831 * trailing copies is done without stripping leading copies, so
1832 * if the separator is `ABA`, then `ABABA` has 1 trailing copy.)
1834 * However, if there is only a single non-empty element, and there
1835 * are no characters in that element not part of the leading or
1836 * trailing separators, then the result is exactly the original value
1839 * Other than for determination of the number of leading and trailing
1840 * copies of the separator, elements consisting only of copies
1841 * of the separator are ignored.
1843 * Returns: (type filename): a newly-allocated string that must be freed with
1847 g_build_path (const gchar
*separator
,
1848 const gchar
*first_element
,
1854 g_return_val_if_fail (separator
!= NULL
, NULL
);
1856 va_start (args
, first_element
);
1857 str
= g_build_path_va (separator
, first_element
, &args
, NULL
);
1866 g_build_pathname_va (const gchar
*first_element
,
1870 /* Code copied from g_build_pathv(), and modified to use two
1871 * alternative single-character separators.
1874 gboolean is_first
= TRUE
;
1875 gboolean have_leading
= FALSE
;
1876 const gchar
*single_element
= NULL
;
1877 const gchar
*next_element
;
1878 const gchar
*last_trailing
= NULL
;
1879 gchar current_separator
= '\\';
1882 result
= g_string_new (NULL
);
1885 next_element
= str_array
[i
++];
1887 next_element
= first_element
;
1891 const gchar
*element
;
1897 element
= next_element
;
1899 next_element
= str_array
[i
++];
1901 next_element
= va_arg (*args
, gchar
*);
1906 /* Ignore empty elements */
1915 (*start
== '\\' || *start
== '/'))
1917 current_separator
= *start
;
1922 end
= start
+ strlen (start
);
1926 while (end
>= start
+ 1 &&
1927 (end
[-1] == '\\' || end
[-1] == '/'))
1929 current_separator
= end
[-1];
1933 last_trailing
= end
;
1934 while (last_trailing
>= element
+ 1 &&
1935 (last_trailing
[-1] == '\\' || last_trailing
[-1] == '/'))
1940 /* If the leading and trailing separator strings are in the
1941 * same element and overlap, the result is exactly that element
1943 if (last_trailing
<= start
)
1944 single_element
= element
;
1946 g_string_append_len (result
, element
, start
- element
);
1947 have_leading
= TRUE
;
1950 single_element
= NULL
;
1957 g_string_append_len (result
, ¤t_separator
, 1);
1959 g_string_append_len (result
, start
, end
- start
);
1965 g_string_free (result
, TRUE
);
1966 return g_strdup (single_element
);
1971 g_string_append (result
, last_trailing
);
1973 return g_string_free (result
, FALSE
);
1980 g_build_filename_va (const gchar
*first_argument
,
1987 str
= g_build_path_va (G_DIR_SEPARATOR_S
, first_argument
, args
, str_array
);
1989 str
= g_build_pathname_va (first_argument
, args
, str_array
);
1996 * g_build_filename_valist:
1997 * @first_element: (type filename): the first element in the path
1998 * @args: va_list of remaining elements in path
2000 * Behaves exactly like g_build_filename(), but takes the path elements
2001 * as a va_list. This function is mainly meant for language bindings.
2003 * Returns: (type filename): a newly-allocated string that must be freed
2009 g_build_filename_valist (const gchar
*first_element
,
2012 g_return_val_if_fail (first_element
!= NULL
, NULL
);
2014 return g_build_filename_va (first_element
, args
, NULL
);
2018 * g_build_filenamev:
2019 * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
2020 * array of strings containing the path elements.
2022 * Behaves exactly like g_build_filename(), but takes the path elements
2023 * as a string array, instead of varargs. This function is mainly
2024 * meant for language bindings.
2026 * Returns: (type filename): a newly-allocated string that must be freed
2032 g_build_filenamev (gchar
**args
)
2034 return g_build_filename_va (NULL
, NULL
, args
);
2039 * @first_element: (type filename): the first element in the path
2040 * @...: remaining elements in path, terminated by %NULL
2042 * Creates a filename from a series of elements using the correct
2043 * separator for filenames.
2045 * On Unix, this function behaves identically to `g_build_path
2046 * (G_DIR_SEPARATOR_S, first_element, ....)`.
2048 * On Windows, it takes into account that either the backslash
2049 * (`\` or slash (`/`) can be used as separator in filenames, but
2050 * otherwise behaves as on UNIX. When file pathname separators need
2051 * to be inserted, the one that last previously occurred in the
2052 * parameters (reading from left to right) is used.
2054 * No attempt is made to force the resulting filename to be an absolute
2055 * path. If the first element is a relative path, the result will
2056 * be a relative path.
2058 * Returns: (type filename): a newly-allocated string that must be freed with
2062 g_build_filename (const gchar
*first_element
,
2068 va_start (args
, first_element
);
2069 str
= g_build_filename_va (first_element
, &args
, NULL
);
2077 * @filename: (type filename): the symbolic link
2078 * @error: return location for a #GError
2080 * Reads the contents of the symbolic link @filename like the POSIX
2081 * readlink() function. The returned string is in the encoding used
2082 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
2084 * Returns: (type filename): A newly-allocated string with the contents of
2085 * the symbolic link, or %NULL if an error occurred.
2090 g_file_read_link (const gchar
*filename
,
2093 #if defined (HAVE_READLINK) || defined (G_OS_WIN32)
2098 g_return_val_if_fail (filename
!= NULL
, NULL
);
2099 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
2102 buffer
= g_malloc (size
);
2107 read_size
= readlink (filename
, buffer
, size
);
2109 read_size
= g_win32_readlink_utf8 (filename
, buffer
, size
);
2113 int saved_errno
= errno
;
2114 set_file_error (error
,
2116 _("Failed to read the symbolic link “%s”: %s"),
2122 if ((size_t) read_size
< size
)
2124 buffer
[read_size
] = 0;
2129 buffer
= g_realloc (buffer
, size
);
2132 g_return_val_if_fail (filename
!= NULL
, NULL
);
2133 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
2135 g_set_error_literal (error
,
2138 _("Symbolic links not supported"));
2145 * g_path_is_absolute:
2146 * @file_name: (type filename): a file name
2148 * Returns %TRUE if the given @file_name is an absolute file name.
2149 * Note that this is a somewhat vague concept on Windows.
2151 * On POSIX systems, an absolute file name is well-defined. It always
2152 * starts from the single root directory. For example "/usr/local".
2154 * On Windows, the concepts of current drive and drive-specific
2155 * current directory introduce vagueness. This function interprets as
2156 * an absolute file name one that either begins with a directory
2157 * separator such as "\Users\tml" or begins with the root on a drive,
2158 * for example "C:\Windows". The first case also includes UNC paths
2159 * such as "\\\\myserver\docs\foo". In all cases, either slashes or
2160 * backslashes are accepted.
2162 * Note that a file name relative to the current drive root does not
2163 * truly specify a file uniquely over time and across processes, as
2164 * the current drive is a per-process value and can be changed.
2166 * File names relative the current directory on some specific drive,
2167 * such as "D:foo/bar", are not interpreted as absolute by this
2168 * function, but they obviously are not relative to the normal current
2169 * directory as returned by getcwd() or g_get_current_dir()
2170 * either. Such paths should be avoided, or need to be handled using
2171 * Windows-specific code.
2173 * Returns: %TRUE if @file_name is absolute
2176 g_path_is_absolute (const gchar
*file_name
)
2178 g_return_val_if_fail (file_name
!= NULL
, FALSE
);
2180 if (G_IS_DIR_SEPARATOR (file_name
[0]))
2184 /* Recognize drive letter on native Windows */
2185 if (g_ascii_isalpha (file_name
[0]) &&
2186 file_name
[1] == ':' && G_IS_DIR_SEPARATOR (file_name
[2]))
2195 * @file_name: (type filename): a file name
2197 * Returns a pointer into @file_name after the root component,
2198 * i.e. after the "/" in UNIX or "C:\" under Windows. If @file_name
2199 * is not an absolute path it returns %NULL.
2201 * Returns: (type filename) (nullable): a pointer into @file_name after the
2205 g_path_skip_root (const gchar
*file_name
)
2207 g_return_val_if_fail (file_name
!= NULL
, NULL
);
2209 #ifdef G_PLATFORM_WIN32
2210 /* Skip \\server\share or //server/share */
2211 if (G_IS_DIR_SEPARATOR (file_name
[0]) &&
2212 G_IS_DIR_SEPARATOR (file_name
[1]) &&
2214 !G_IS_DIR_SEPARATOR (file_name
[2]))
2217 p
= strchr (file_name
+ 2, G_DIR_SEPARATOR
);
2223 q
= strchr (file_name
+ 2, '/');
2224 if (p
== NULL
|| (q
!= NULL
&& q
< p
))
2229 if (p
&& p
> file_name
+ 2 && p
[1])
2233 while (file_name
[0] && !G_IS_DIR_SEPARATOR (file_name
[0]))
2236 /* Possibly skip a backslash after the share name */
2237 if (G_IS_DIR_SEPARATOR (file_name
[0]))
2240 return (gchar
*)file_name
;
2245 /* Skip initial slashes */
2246 if (G_IS_DIR_SEPARATOR (file_name
[0]))
2248 while (G_IS_DIR_SEPARATOR (file_name
[0]))
2250 return (gchar
*)file_name
;
2255 if (g_ascii_isalpha (file_name
[0]) &&
2256 file_name
[1] == ':' &&
2257 G_IS_DIR_SEPARATOR (file_name
[2]))
2258 return (gchar
*)file_name
+ 3;
2266 * @file_name: (type filename): the name of the file
2268 * Gets the name of the file without any leading directory
2269 * components. It returns a pointer into the given file name
2272 * Returns: (type filename): the name of the file without any leading
2273 * directory components
2275 * Deprecated:2.2: Use g_path_get_basename() instead, but notice
2276 * that g_path_get_basename() allocates new memory for the
2277 * returned string, unlike this function which returns a pointer
2278 * into the argument.
2281 g_basename (const gchar
*file_name
)
2285 g_return_val_if_fail (file_name
!= NULL
, NULL
);
2287 base
= strrchr (file_name
, G_DIR_SEPARATOR
);
2292 q
= strrchr (file_name
, '/');
2293 if (base
== NULL
|| (q
!= NULL
&& q
> base
))
2302 if (g_ascii_isalpha (file_name
[0]) && file_name
[1] == ':')
2303 return (gchar
*) file_name
+ 2;
2306 return (gchar
*) file_name
;
2310 * g_path_get_basename:
2311 * @file_name: (type filename): the name of the file
2313 * Gets the last component of the filename.
2315 * If @file_name ends with a directory separator it gets the component
2316 * before the last slash. If @file_name consists only of directory
2317 * separators (and on Windows, possibly a drive letter), a single
2318 * separator is returned. If @file_name is empty, it gets ".".
2320 * Returns: (type filename): a newly allocated string containing the last
2321 * component of the filename
2324 g_path_get_basename (const gchar
*file_name
)
2327 gssize last_nonslash
;
2331 g_return_val_if_fail (file_name
!= NULL
, NULL
);
2333 if (file_name
[0] == '\0')
2334 return g_strdup (".");
2336 last_nonslash
= strlen (file_name
) - 1;
2338 while (last_nonslash
>= 0 && G_IS_DIR_SEPARATOR (file_name
[last_nonslash
]))
2341 if (last_nonslash
== -1)
2342 /* string only containing slashes */
2343 return g_strdup (G_DIR_SEPARATOR_S
);
2346 if (last_nonslash
== 1 &&
2347 g_ascii_isalpha (file_name
[0]) &&
2348 file_name
[1] == ':')
2349 /* string only containing slashes and a drive */
2350 return g_strdup (G_DIR_SEPARATOR_S
);
2352 base
= last_nonslash
;
2354 while (base
>=0 && !G_IS_DIR_SEPARATOR (file_name
[base
]))
2359 g_ascii_isalpha (file_name
[0]) &&
2360 file_name
[1] == ':')
2362 #endif /* G_OS_WIN32 */
2364 len
= last_nonslash
- base
;
2365 retval
= g_malloc (len
+ 1);
2366 memcpy (retval
, file_name
+ base
+ 1, len
);
2367 retval
[len
] = '\0';
2374 * @file_name: (type filename): the name of the file
2376 * Gets the directory components of a file name.
2378 * If the file name has no directory components "." is returned.
2379 * The returned string should be freed when no longer needed.
2381 * Returns: (type filename): the directory components of the file
2383 * Deprecated: use g_path_get_dirname() instead
2387 * g_path_get_dirname:
2388 * @file_name: (type filename): the name of the file
2390 * Gets the directory components of a file name.
2392 * If the file name has no directory components "." is returned.
2393 * The returned string should be freed when no longer needed.
2395 * Returns: (type filename): the directory components of the file
2398 g_path_get_dirname (const gchar
*file_name
)
2403 g_return_val_if_fail (file_name
!= NULL
, NULL
);
2405 base
= strrchr (file_name
, G_DIR_SEPARATOR
);
2410 q
= strrchr (file_name
, '/');
2411 if (base
== NULL
|| (q
!= NULL
&& q
> base
))
2419 if (g_ascii_isalpha (file_name
[0]) && file_name
[1] == ':')
2421 gchar drive_colon_dot
[4];
2423 drive_colon_dot
[0] = file_name
[0];
2424 drive_colon_dot
[1] = ':';
2425 drive_colon_dot
[2] = '.';
2426 drive_colon_dot
[3] = '\0';
2428 return g_strdup (drive_colon_dot
);
2431 return g_strdup (".");
2434 while (base
> file_name
&& G_IS_DIR_SEPARATOR (*base
))
2438 /* base points to the char before the last slash.
2440 * In case file_name is the root of a drive (X:\) or a child of the
2441 * root of a drive (X:\foo), include the slash.
2443 * In case file_name is the root share of an UNC path
2444 * (\\server\share), add a slash, returning \\server\share\ .
2446 * In case file_name is a direct child of a share in an UNC path
2447 * (\\server\share\foo), include the slash after the share name,
2448 * returning \\server\share\ .
2450 if (base
== file_name
+ 1 &&
2451 g_ascii_isalpha (file_name
[0]) &&
2452 file_name
[1] == ':')
2454 else if (G_IS_DIR_SEPARATOR (file_name
[0]) &&
2455 G_IS_DIR_SEPARATOR (file_name
[1]) &&
2457 !G_IS_DIR_SEPARATOR (file_name
[2]) &&
2458 base
>= file_name
+ 2)
2460 const gchar
*p
= file_name
+ 2;
2461 while (*p
&& !G_IS_DIR_SEPARATOR (*p
))
2465 len
= (guint
) strlen (file_name
) + 1;
2466 base
= g_new (gchar
, len
+ 1);
2467 strcpy (base
, file_name
);
2468 base
[len
-1] = G_DIR_SEPARATOR
;
2472 if (G_IS_DIR_SEPARATOR (*p
))
2475 while (*p
&& !G_IS_DIR_SEPARATOR (*p
))
2483 len
= (guint
) 1 + base
- file_name
;
2484 base
= g_new (gchar
, len
+ 1);
2485 memmove (base
, file_name
, len
);
2492 * g_canonicalize_filename:
2493 * @filename: (type filename): the name of the file
2494 * @relative_to: (type filename) (nullable): the relative directory, or %NULL
2495 * to use the current working directory
2497 * Gets the canonical file name from @filename. All triple slashes are turned into
2498 * single slashes, and all `..` and `.`s resolved against @relative_to.
2500 * Symlinks are not followed, and the returned path is guaranteed to be absolute.
2502 * If @filename is an absolute path, @relative_to is ignored. Otherwise,
2503 * @relative_to will be prepended to @filename to make it absolute. @relative_to
2504 * must be an absolute path, or %NULL. If @relative_to is %NULL, it'll fallback
2505 * to g_get_current_dir().
2507 * This function never fails, and will canonicalize file paths even if they don't
2510 * No file system I/O is done.
2512 * Returns: (type filename) (transfer full): a newly allocated string with the
2513 * canonical file path
2517 g_canonicalize_filename (const gchar
*filename
,
2518 const gchar
*relative_to
)
2520 gchar
*canon
, *start
, *p
, *q
;
2523 g_return_val_if_fail (relative_to
== NULL
|| g_path_is_absolute (relative_to
), NULL
);
2525 if (!g_path_is_absolute (filename
))
2527 gchar
*cwd_allocated
= NULL
;
2530 if (relative_to
!= NULL
)
2533 cwd
= cwd_allocated
= g_get_current_dir ();
2535 canon
= g_build_filename (cwd
, filename
, NULL
);
2536 g_free (cwd_allocated
);
2540 canon
= g_strdup (filename
);
2543 start
= (char *)g_path_skip_root (canon
);
2547 /* This shouldn't really happen, as g_get_current_dir() should
2548 return an absolute pathname, but bug 573843 shows this is
2549 not always happening */
2551 return g_build_filename (G_DIR_SEPARATOR_S
, filename
, NULL
);
2554 /* POSIX allows double slashes at the start to
2555 * mean something special (as does windows too).
2556 * So, "//" != "/", but more than two slashes
2557 * is treated as "/".
2562 G_IS_DIR_SEPARATOR (*p
);
2569 memmove (start
, start
+i
, strlen (start
+i
) + 1);
2572 /* Make sure we're using the canonical dir separator */
2574 while (p
< start
&& G_IS_DIR_SEPARATOR (*p
))
2575 *p
++ = G_DIR_SEPARATOR
;
2580 if (p
[0] == '.' && (p
[1] == 0 || G_IS_DIR_SEPARATOR (p
[1])))
2582 memmove (p
, p
+1, strlen (p
+1)+1);
2584 else if (p
[0] == '.' && p
[1] == '.' && (p
[2] == 0 || G_IS_DIR_SEPARATOR (p
[2])))
2587 /* Skip previous separator */
2591 while (p
> start
&& !G_IS_DIR_SEPARATOR (*p
))
2593 if (G_IS_DIR_SEPARATOR (*p
))
2594 *p
++ = G_DIR_SEPARATOR
;
2595 memmove (p
, q
, strlen (q
)+1);
2599 /* Skip until next separator */
2600 while (*p
!= 0 && !G_IS_DIR_SEPARATOR (*p
))
2605 /* Canonicalize one separator */
2606 *p
++ = G_DIR_SEPARATOR
;
2610 /* Remove additional separators */
2612 while (*q
&& G_IS_DIR_SEPARATOR (*q
))
2616 memmove (p
, q
, strlen (q
) + 1);
2619 /* Remove trailing slashes */
2620 if (p
> start
&& G_IS_DIR_SEPARATOR (*(p
-1)))
2626 #if defined(MAXPATHLEN)
2627 #define G_PATH_LENGTH MAXPATHLEN
2628 #elif defined(PATH_MAX)
2629 #define G_PATH_LENGTH PATH_MAX
2630 #elif defined(_PC_PATH_MAX)
2631 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
2633 #define G_PATH_LENGTH 2048
2637 * g_get_current_dir:
2639 * Gets the current directory.
2641 * The returned string should be freed when no longer needed.
2642 * The encoding of the returned string is system defined.
2643 * On Windows, it is always UTF-8.
2645 * Since GLib 2.40, this function will return the value of the "PWD"
2646 * environment variable if it is set and it happens to be the same as
2647 * the current directory. This can make a difference in the case that
2648 * the current directory is the target of a symbolic link.
2650 * Returns: (type filename): the current directory
2653 g_get_current_dir (void)
2658 wchar_t dummy
[2], *wdir
;
2661 len
= GetCurrentDirectoryW (2, dummy
);
2662 wdir
= g_new (wchar_t, len
);
2664 if (GetCurrentDirectoryW (len
, wdir
) == len
- 1)
2665 dir
= g_utf16_to_utf8 (wdir
, -1, NULL
, NULL
, NULL
);
2670 dir
= g_strdup ("\\");
2676 gchar
*buffer
= NULL
;
2678 static gulong max_len
= 0;
2679 struct stat pwdbuf
, dotbuf
;
2681 pwd
= g_getenv ("PWD");
2683 g_stat (".", &dotbuf
) == 0 && g_stat (pwd
, &pwdbuf
) == 0 &&
2684 dotbuf
.st_dev
== pwdbuf
.st_dev
&& dotbuf
.st_ino
== pwdbuf
.st_ino
)
2685 return g_strdup (pwd
);
2688 max_len
= (G_PATH_LENGTH
== -1) ? 2048 : G_PATH_LENGTH
;
2690 while (max_len
< G_MAXULONG
/ 2)
2693 buffer
= g_new (gchar
, max_len
+ 1);
2695 dir
= getcwd (buffer
, max_len
);
2697 if (dir
|| errno
!= ERANGE
)
2703 if (!dir
|| !*buffer
)
2705 /* hm, should we g_error() out here?
2706 * this can happen if e.g. "./" has mode \0000
2708 buffer
[0] = G_DIR_SEPARATOR
;
2712 dir
= g_strdup (buffer
);
2717 #endif /* !G_OS_WIN32 */
2722 /* Binary compatibility versions. Not for newly compiled code. */
2724 _GLIB_EXTERN gboolean
g_file_test_utf8 (const gchar
*filename
,
2726 _GLIB_EXTERN gboolean
g_file_get_contents_utf8 (const gchar
*filename
,
2730 _GLIB_EXTERN gint
g_mkstemp_utf8 (gchar
*tmpl
);
2731 _GLIB_EXTERN gint
g_file_open_tmp_utf8 (const gchar
*tmpl
,
2734 _GLIB_EXTERN gchar
*g_get_current_dir_utf8 (void);
2738 g_file_test_utf8 (const gchar
*filename
,
2741 return g_file_test (filename
, test
);
2745 g_file_get_contents_utf8 (const gchar
*filename
,
2750 return g_file_get_contents (filename
, contents
, length
, error
);
2754 g_mkstemp_utf8 (gchar
*tmpl
)
2756 return g_mkstemp (tmpl
);
2760 g_file_open_tmp_utf8 (const gchar
*tmpl
,
2764 return g_file_open_tmp (tmpl
, name_used
, error
);
2768 g_get_current_dir_utf8 (void)
2770 return g_get_current_dir ();