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 Windows renaming a file will not remove an existing file with the
1177 * new name, so on Windows there is a race condition between the existing
1178 * file being removed and the temporary file being renamed.
1180 * - On Windows there is no way to remove a file that is open to some
1181 * process, or mapped into memory. Thus, this function will fail if
1182 * @filename already exists and is open.
1184 * If the call was successful, it returns %TRUE. If the call was not successful,
1185 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1186 * Possible error codes are those in the #GFileError enumeration.
1188 * Note that the name for the temporary file is constructed by appending up
1189 * to 7 characters to @filename.
1191 * Returns: %TRUE on success, %FALSE if an error occurred
1196 g_file_set_contents (const gchar
*filename
,
1197 const gchar
*contents
,
1201 gchar
*tmp_filename
;
1203 GError
*rename_error
= NULL
;
1205 g_return_val_if_fail (filename
!= NULL
, FALSE
);
1206 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, FALSE
);
1207 g_return_val_if_fail (contents
!= NULL
|| length
== 0, FALSE
);
1208 g_return_val_if_fail (length
>= -1, FALSE
);
1211 length
= strlen (contents
);
1213 tmp_filename
= write_to_temp_file (contents
, length
, filename
, error
);
1221 if (!rename_file (tmp_filename
, filename
, &rename_error
))
1225 g_unlink (tmp_filename
);
1226 g_propagate_error (error
, rename_error
);
1230 #else /* G_OS_WIN32 */
1232 /* Renaming failed, but on Windows this may just mean
1233 * the file already exists. So if the target file
1234 * exists, try deleting it and do the rename again.
1236 if (!g_file_test (filename
, G_FILE_TEST_EXISTS
))
1238 g_unlink (tmp_filename
);
1239 g_propagate_error (error
, rename_error
);
1244 g_error_free (rename_error
);
1246 if (g_unlink (filename
) == -1)
1248 int saved_errno
= errno
;
1249 set_file_error (error
,
1251 _("Existing file “%s” could not be removed: g_unlink() failed: %s"),
1253 g_unlink (tmp_filename
);
1258 if (!rename_file (tmp_filename
, filename
, error
))
1260 g_unlink (tmp_filename
);
1271 g_free (tmp_filename
);
1276 * get_tmp_file based on the mkstemp implementation from the GNU C library.
1277 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1279 typedef gint (*GTmpFileCallback
) (const gchar
*, gint
, gint
);
1282 get_tmp_file (gchar
*tmpl
,
1289 static const char letters
[] =
1290 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1291 static const int NLETTERS
= sizeof (letters
) - 1;
1294 static int counter
= 0;
1296 g_return_val_if_fail (tmpl
!= NULL
, -1);
1298 /* find the last occurrence of "XXXXXX" */
1299 XXXXXX
= g_strrstr (tmpl
, "XXXXXX");
1301 if (!XXXXXX
|| strncmp (XXXXXX
, "XXXXXX", 6))
1307 /* Get some more or less random data. */
1308 g_get_current_time (&tv
);
1309 value
= (tv
.tv_usec
^ tv
.tv_sec
) + counter
++;
1311 for (count
= 0; count
< 100; value
+= 7777, ++count
)
1315 /* Fill in the random bits. */
1316 XXXXXX
[0] = letters
[v
% NLETTERS
];
1318 XXXXXX
[1] = letters
[v
% NLETTERS
];
1320 XXXXXX
[2] = letters
[v
% NLETTERS
];
1322 XXXXXX
[3] = letters
[v
% NLETTERS
];
1324 XXXXXX
[4] = letters
[v
% NLETTERS
];
1326 XXXXXX
[5] = letters
[v
% NLETTERS
];
1328 fd
= f (tmpl
, flags
, mode
);
1332 else if (errno
!= EEXIST
)
1333 /* Any other error will apply also to other names we might
1334 * try, and there are 2^32 or so of them, so give up now.
1339 /* We got out of the loop because we ran out of combinations to try. */
1344 /* Some GTmpFileCallback implementations.
1346 * Note: we cannot use open() or g_open() directly because even though
1347 * they appear compatible, they may be vararg functions and calling
1348 * varargs functions through a non-varargs type is undefined.
1351 wrap_g_mkdir (const gchar
*filename
,
1352 int flags G_GNUC_UNUSED
,
1355 /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1356 return g_mkdir (filename
, mode
);
1360 wrap_g_open (const gchar
*filename
,
1364 return g_open (filename
, flags
, mode
);
1368 * g_mkdtemp_full: (skip)
1369 * @tmpl: (type filename): template directory name
1370 * @mode: permissions to create the temporary directory with
1372 * Creates a temporary directory. See the mkdtemp() documentation
1373 * on most UNIX-like systems.
1375 * The parameter is a string that should follow the rules for
1376 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1377 * g_mkdtemp_full() is slightly more flexible than mkdtemp() in that the
1378 * sequence does not have to occur at the very end of the template
1379 * and you can pass a @mode. The X string will be modified to form
1380 * the name of a directory that didn't exist. The string should be
1381 * in the GLib file name encoding. Most importantly, on Windows it
1382 * should be in UTF-8.
1384 * If you are going to be creating a temporary directory inside the
1385 * directory returned by g_get_tmp_dir(), you might want to use
1386 * g_dir_make_tmp() instead.
1388 * Returns: (nullable) (type filename): A pointer to @tmpl, which has been
1389 * modified to hold the directory name. In case of errors, %NULL is
1390 * returned, and %errno will be set.
1395 g_mkdtemp_full (gchar
*tmpl
,
1398 if (get_tmp_file (tmpl
, wrap_g_mkdir
, 0, mode
) == -1)
1406 * @tmpl: (type filename): template directory name
1408 * Creates a temporary directory. See the mkdtemp() documentation
1409 * on most UNIX-like systems.
1411 * The parameter is a string that should follow the rules for
1412 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1413 * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1414 * sequence does not have to occur at the very end of the template.
1415 * The X string will be modified to form the name of a directory that
1417 * The string should be in the GLib file name encoding. Most importantly,
1418 * on Windows it should be in UTF-8.
1420 * If you are going to be creating a temporary directory inside the
1421 * directory returned by g_get_tmp_dir(), you might want to use
1422 * g_dir_make_tmp() instead.
1424 * Returns: (nullable) (type filename): A pointer to @tmpl, which has been
1425 * modified to hold the directory name. In case of errors, %NULL is
1426 * returned and %errno will be set.
1431 g_mkdtemp (gchar
*tmpl
)
1433 return g_mkdtemp_full (tmpl
, 0700);
1437 * g_mkstemp_full: (skip)
1438 * @tmpl: (type filename): template filename
1439 * @flags: flags to pass to an open() call in addition to O_EXCL
1440 * and O_CREAT, which are passed automatically
1441 * @mode: permissions to create the temporary file with
1443 * Opens a temporary file. See the mkstemp() documentation
1444 * on most UNIX-like systems.
1446 * The parameter is a string that should follow the rules for
1447 * mkstemp() templates, i.e. contain the string "XXXXXX".
1448 * g_mkstemp_full() is slightly more flexible than mkstemp()
1449 * in that the sequence does not have to occur at the very end of the
1450 * template and you can pass a @mode and additional @flags. The X
1451 * string will be modified to form the name of a file that didn't exist.
1452 * The string should be in the GLib file name encoding. Most importantly,
1453 * on Windows it should be in UTF-8.
1455 * Returns: A file handle (as from open()) to the file
1456 * opened for reading and writing. The file handle should be
1457 * closed with close(). In case of errors, -1 is returned
1458 * and %errno will be set.
1463 g_mkstemp_full (gchar
*tmpl
,
1467 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1468 return get_tmp_file (tmpl
, wrap_g_open
,
1469 flags
| O_CREAT
| O_EXCL
, mode
);
1474 * @tmpl: (type filename): template filename
1476 * Opens a temporary file. See the mkstemp() documentation
1477 * on most UNIX-like systems.
1479 * The parameter is a string that should follow the rules for
1480 * mkstemp() templates, i.e. contain the string "XXXXXX".
1481 * g_mkstemp() is slightly more flexible than mkstemp() in that the
1482 * sequence does not have to occur at the very end of the template.
1483 * The X string will be modified to form the name of a file that
1484 * didn't exist. The string should be in the GLib file name encoding.
1485 * Most importantly, on Windows it should be in UTF-8.
1487 * Returns: A file handle (as from open()) to the file
1488 * opened for reading and writing. The file is opened in binary
1489 * mode on platforms where there is a difference. The file handle
1490 * should be closed with close(). In case of errors, -1 is
1491 * returned and %errno will be set.
1494 g_mkstemp (gchar
*tmpl
)
1496 return g_mkstemp_full (tmpl
, O_RDWR
| O_BINARY
, 0600);
1500 g_get_tmp_name (const gchar
*tmpl
,
1516 if ((slash
= strchr (tmpl
, G_DIR_SEPARATOR
)) != NULL
1518 || (strchr (tmpl
, '/') != NULL
&& (slash
= "/"))
1522 gchar
*display_tmpl
= g_filename_display_name (tmpl
);
1529 G_FILE_ERROR_FAILED
,
1530 _("Template “%s” invalid, should not contain a “%s”"),
1532 g_free (display_tmpl
);
1537 if (strstr (tmpl
, "XXXXXX") == NULL
)
1539 gchar
*display_tmpl
= g_filename_display_name (tmpl
);
1542 G_FILE_ERROR_FAILED
,
1543 _("Template “%s” doesn’t contain XXXXXX"),
1545 g_free (display_tmpl
);
1549 tmpdir
= g_get_tmp_dir ();
1551 if (G_IS_DIR_SEPARATOR (tmpdir
[strlen (tmpdir
) - 1]))
1554 sep
= G_DIR_SEPARATOR_S
;
1556 fulltemplate
= g_strconcat (tmpdir
, sep
, tmpl
, NULL
);
1558 retval
= get_tmp_file (fulltemplate
, f
, flags
, mode
);
1561 int saved_errno
= errno
;
1562 set_file_error (error
,
1564 _("Failed to create file “%s”: %s"),
1566 g_free (fulltemplate
);
1570 *name_used
= fulltemplate
;
1577 * @tmpl: (type filename) (nullable): Template for file name, as in
1578 * g_mkstemp(), basename only, or %NULL for a default template
1579 * @name_used: (out) (type filename): location to store actual name used,
1581 * @error: return location for a #GError
1583 * Opens a file for writing in the preferred directory for temporary
1584 * files (as returned by g_get_tmp_dir()).
1586 * @tmpl should be a string in the GLib file name encoding containing
1587 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1588 * However, unlike these functions, the template should only be a
1589 * basename, no directory components are allowed. If template is
1590 * %NULL, a default template is used.
1592 * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
1593 * modified, and might thus be a read-only literal string.
1595 * Upon success, and if @name_used is non-%NULL, the actual name used
1596 * is returned in @name_used. This string should be freed with g_free()
1597 * when not needed any longer. The returned name is in the GLib file
1600 * Returns: A file handle (as from open()) to the file opened for
1601 * reading and writing. The file is opened in binary mode on platforms
1602 * where there is a difference. The file handle should be closed with
1603 * close(). In case of errors, -1 is returned and @error will be set.
1606 g_file_open_tmp (const gchar
*tmpl
,
1610 gchar
*fulltemplate
;
1613 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, -1);
1615 result
= g_get_tmp_name (tmpl
, &fulltemplate
,
1617 O_CREAT
| O_EXCL
| O_RDWR
| O_BINARY
,
1623 *name_used
= fulltemplate
;
1625 g_free (fulltemplate
);
1633 * @tmpl: (type filename) (nullable): Template for directory name,
1634 * as in g_mkdtemp(), basename only, or %NULL for a default template
1635 * @error: return location for a #GError
1637 * Creates a subdirectory in the preferred directory for temporary
1638 * files (as returned by g_get_tmp_dir()).
1640 * @tmpl should be a string in the GLib file name encoding containing
1641 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1642 * However, unlike these functions, the template should only be a
1643 * basename, no directory components are allowed. If template is
1644 * %NULL, a default template is used.
1646 * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
1647 * modified, and might thus be a read-only literal string.
1649 * Returns: (type filename): The actual name used. This string
1650 * should be freed with g_free() when not needed any longer and is
1651 * is in the GLib file name encoding. In case of errors, %NULL is
1652 * returned and @error will be set.
1657 g_dir_make_tmp (const gchar
*tmpl
,
1660 gchar
*fulltemplate
;
1662 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
1664 if (g_get_tmp_name (tmpl
, &fulltemplate
, wrap_g_mkdir
, 0, 0700, error
) == -1)
1667 return fulltemplate
;
1671 g_build_path_va (const gchar
*separator
,
1672 const gchar
*first_element
,
1677 gint separator_len
= strlen (separator
);
1678 gboolean is_first
= TRUE
;
1679 gboolean have_leading
= FALSE
;
1680 const gchar
*single_element
= NULL
;
1681 const gchar
*next_element
;
1682 const gchar
*last_trailing
= NULL
;
1685 result
= g_string_new (NULL
);
1688 next_element
= str_array
[i
++];
1690 next_element
= first_element
;
1694 const gchar
*element
;
1700 element
= next_element
;
1702 next_element
= str_array
[i
++];
1704 next_element
= va_arg (*args
, gchar
*);
1709 /* Ignore empty elements */
1717 while (strncmp (start
, separator
, separator_len
) == 0)
1718 start
+= separator_len
;
1721 end
= start
+ strlen (start
);
1725 while (end
>= start
+ separator_len
&&
1726 strncmp (end
- separator_len
, separator
, separator_len
) == 0)
1727 end
-= separator_len
;
1729 last_trailing
= end
;
1730 while (last_trailing
>= element
+ separator_len
&&
1731 strncmp (last_trailing
- separator_len
, separator
, separator_len
) == 0)
1732 last_trailing
-= separator_len
;
1736 /* If the leading and trailing separator strings are in the
1737 * same element and overlap, the result is exactly that element
1739 if (last_trailing
<= start
)
1740 single_element
= element
;
1742 g_string_append_len (result
, element
, start
- element
);
1743 have_leading
= TRUE
;
1746 single_element
= NULL
;
1753 g_string_append (result
, separator
);
1755 g_string_append_len (result
, start
, end
- start
);
1761 g_string_free (result
, TRUE
);
1762 return g_strdup (single_element
);
1767 g_string_append (result
, last_trailing
);
1769 return g_string_free (result
, FALSE
);
1775 * @separator: a string used to separator the elements of the path.
1776 * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
1777 * array of strings containing the path elements.
1779 * Behaves exactly like g_build_path(), but takes the path elements
1780 * as a string array, instead of varargs. This function is mainly
1781 * meant for language bindings.
1783 * Returns: (type filename): a newly-allocated string that must be freed
1789 g_build_pathv (const gchar
*separator
,
1795 return g_build_path_va (separator
, NULL
, NULL
, args
);
1801 * @separator: (type filename): a string used to separator the elements of the path.
1802 * @first_element: (type filename): the first element in the path
1803 * @...: remaining elements in path, terminated by %NULL
1805 * Creates a path from a series of elements using @separator as the
1806 * separator between elements. At the boundary between two elements,
1807 * any trailing occurrences of separator in the first element, or
1808 * leading occurrences of separator in the second element are removed
1809 * and exactly one copy of the separator is inserted.
1811 * Empty elements are ignored.
1813 * The number of leading copies of the separator on the result is
1814 * the same as the number of leading copies of the separator on
1815 * the first non-empty element.
1817 * The number of trailing copies of the separator on the result is
1818 * the same as the number of trailing copies of the separator on
1819 * the last non-empty element. (Determination of the number of
1820 * trailing copies is done without stripping leading copies, so
1821 * if the separator is `ABA`, then `ABABA` has 1 trailing copy.)
1823 * However, if there is only a single non-empty element, and there
1824 * are no characters in that element not part of the leading or
1825 * trailing separators, then the result is exactly the original value
1828 * Other than for determination of the number of leading and trailing
1829 * copies of the separator, elements consisting only of copies
1830 * of the separator are ignored.
1832 * Returns: (type filename): a newly-allocated string that must be freed with
1836 g_build_path (const gchar
*separator
,
1837 const gchar
*first_element
,
1843 g_return_val_if_fail (separator
!= NULL
, NULL
);
1845 va_start (args
, first_element
);
1846 str
= g_build_path_va (separator
, first_element
, &args
, NULL
);
1855 g_build_pathname_va (const gchar
*first_element
,
1859 /* Code copied from g_build_pathv(), and modified to use two
1860 * alternative single-character separators.
1863 gboolean is_first
= TRUE
;
1864 gboolean have_leading
= FALSE
;
1865 const gchar
*single_element
= NULL
;
1866 const gchar
*next_element
;
1867 const gchar
*last_trailing
= NULL
;
1868 gchar current_separator
= '\\';
1871 result
= g_string_new (NULL
);
1874 next_element
= str_array
[i
++];
1876 next_element
= first_element
;
1880 const gchar
*element
;
1886 element
= next_element
;
1888 next_element
= str_array
[i
++];
1890 next_element
= va_arg (*args
, gchar
*);
1895 /* Ignore empty elements */
1904 (*start
== '\\' || *start
== '/'))
1906 current_separator
= *start
;
1911 end
= start
+ strlen (start
);
1915 while (end
>= start
+ 1 &&
1916 (end
[-1] == '\\' || end
[-1] == '/'))
1918 current_separator
= end
[-1];
1922 last_trailing
= end
;
1923 while (last_trailing
>= element
+ 1 &&
1924 (last_trailing
[-1] == '\\' || last_trailing
[-1] == '/'))
1929 /* If the leading and trailing separator strings are in the
1930 * same element and overlap, the result is exactly that element
1932 if (last_trailing
<= start
)
1933 single_element
= element
;
1935 g_string_append_len (result
, element
, start
- element
);
1936 have_leading
= TRUE
;
1939 single_element
= NULL
;
1946 g_string_append_len (result
, ¤t_separator
, 1);
1948 g_string_append_len (result
, start
, end
- start
);
1954 g_string_free (result
, TRUE
);
1955 return g_strdup (single_element
);
1960 g_string_append (result
, last_trailing
);
1962 return g_string_free (result
, FALSE
);
1969 g_build_filename_va (const gchar
*first_argument
,
1976 str
= g_build_path_va (G_DIR_SEPARATOR_S
, first_argument
, args
, str_array
);
1978 str
= g_build_pathname_va (first_argument
, args
, str_array
);
1985 * g_build_filename_valist:
1986 * @first_element: (type filename): the first element in the path
1987 * @args: va_list of remaining elements in path
1989 * Behaves exactly like g_build_filename(), but takes the path elements
1990 * as a va_list. This function is mainly meant for language bindings.
1992 * Returns: (type filename): a newly-allocated string that must be freed
1998 g_build_filename_valist (const gchar
*first_element
,
2001 g_return_val_if_fail (first_element
!= NULL
, NULL
);
2003 return g_build_filename_va (first_element
, args
, NULL
);
2007 * g_build_filenamev:
2008 * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
2009 * array of strings containing the path elements.
2011 * Behaves exactly like g_build_filename(), but takes the path elements
2012 * as a string array, instead of varargs. This function is mainly
2013 * meant for language bindings.
2015 * Returns: (type filename): a newly-allocated string that must be freed
2021 g_build_filenamev (gchar
**args
)
2023 return g_build_filename_va (NULL
, NULL
, args
);
2028 * @first_element: (type filename): the first element in the path
2029 * @...: remaining elements in path, terminated by %NULL
2031 * Creates a filename from a series of elements using the correct
2032 * separator for filenames.
2034 * On Unix, this function behaves identically to `g_build_path
2035 * (G_DIR_SEPARATOR_S, first_element, ....)`.
2037 * On Windows, it takes into account that either the backslash
2038 * (`\` or slash (`/`) can be used as separator in filenames, but
2039 * otherwise behaves as on UNIX. When file pathname separators need
2040 * to be inserted, the one that last previously occurred in the
2041 * parameters (reading from left to right) is used.
2043 * No attempt is made to force the resulting filename to be an absolute
2044 * path. If the first element is a relative path, the result will
2045 * be a relative path.
2047 * Returns: (type filename): a newly-allocated string that must be freed with
2051 g_build_filename (const gchar
*first_element
,
2057 va_start (args
, first_element
);
2058 str
= g_build_filename_va (first_element
, &args
, NULL
);
2066 * @filename: (type filename): the symbolic link
2067 * @error: return location for a #GError
2069 * Reads the contents of the symbolic link @filename like the POSIX
2070 * readlink() function. The returned string is in the encoding used
2071 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
2073 * Returns: (type filename): A newly-allocated string with the contents of
2074 * the symbolic link, or %NULL if an error occurred.
2079 g_file_read_link (const gchar
*filename
,
2082 #if defined (HAVE_READLINK) || defined (G_OS_WIN32)
2087 g_return_val_if_fail (filename
!= NULL
, NULL
);
2088 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
2091 buffer
= g_malloc (size
);
2096 read_size
= readlink (filename
, buffer
, size
);
2098 read_size
= g_win32_readlink_utf8 (filename
, buffer
, size
);
2102 int saved_errno
= errno
;
2103 set_file_error (error
,
2105 _("Failed to read the symbolic link “%s”: %s"),
2111 if ((size_t) read_size
< size
)
2113 buffer
[read_size
] = 0;
2118 buffer
= g_realloc (buffer
, size
);
2121 g_return_val_if_fail (filename
!= NULL
, NULL
);
2122 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, NULL
);
2124 g_set_error_literal (error
,
2127 _("Symbolic links not supported"));
2134 * g_path_is_absolute:
2135 * @file_name: (type filename): a file name
2137 * Returns %TRUE if the given @file_name is an absolute file name.
2138 * Note that this is a somewhat vague concept on Windows.
2140 * On POSIX systems, an absolute file name is well-defined. It always
2141 * starts from the single root directory. For example "/usr/local".
2143 * On Windows, the concepts of current drive and drive-specific
2144 * current directory introduce vagueness. This function interprets as
2145 * an absolute file name one that either begins with a directory
2146 * separator such as "\Users\tml" or begins with the root on a drive,
2147 * for example "C:\Windows". The first case also includes UNC paths
2148 * such as "\\\\myserver\docs\foo". In all cases, either slashes or
2149 * backslashes are accepted.
2151 * Note that a file name relative to the current drive root does not
2152 * truly specify a file uniquely over time and across processes, as
2153 * the current drive is a per-process value and can be changed.
2155 * File names relative the current directory on some specific drive,
2156 * such as "D:foo/bar", are not interpreted as absolute by this
2157 * function, but they obviously are not relative to the normal current
2158 * directory as returned by getcwd() or g_get_current_dir()
2159 * either. Such paths should be avoided, or need to be handled using
2160 * Windows-specific code.
2162 * Returns: %TRUE if @file_name is absolute
2165 g_path_is_absolute (const gchar
*file_name
)
2167 g_return_val_if_fail (file_name
!= NULL
, FALSE
);
2169 if (G_IS_DIR_SEPARATOR (file_name
[0]))
2173 /* Recognize drive letter on native Windows */
2174 if (g_ascii_isalpha (file_name
[0]) &&
2175 file_name
[1] == ':' && G_IS_DIR_SEPARATOR (file_name
[2]))
2184 * @file_name: (type filename): a file name
2186 * Returns a pointer into @file_name after the root component,
2187 * i.e. after the "/" in UNIX or "C:\" under Windows. If @file_name
2188 * is not an absolute path it returns %NULL.
2190 * Returns: (type filename) (nullable): a pointer into @file_name after the
2194 g_path_skip_root (const gchar
*file_name
)
2196 g_return_val_if_fail (file_name
!= NULL
, NULL
);
2198 #ifdef G_PLATFORM_WIN32
2199 /* Skip \\server\share or //server/share */
2200 if (G_IS_DIR_SEPARATOR (file_name
[0]) &&
2201 G_IS_DIR_SEPARATOR (file_name
[1]) &&
2203 !G_IS_DIR_SEPARATOR (file_name
[2]))
2206 p
= strchr (file_name
+ 2, G_DIR_SEPARATOR
);
2212 q
= strchr (file_name
+ 2, '/');
2213 if (p
== NULL
|| (q
!= NULL
&& q
< p
))
2218 if (p
&& p
> file_name
+ 2 && p
[1])
2222 while (file_name
[0] && !G_IS_DIR_SEPARATOR (file_name
[0]))
2225 /* Possibly skip a backslash after the share name */
2226 if (G_IS_DIR_SEPARATOR (file_name
[0]))
2229 return (gchar
*)file_name
;
2234 /* Skip initial slashes */
2235 if (G_IS_DIR_SEPARATOR (file_name
[0]))
2237 while (G_IS_DIR_SEPARATOR (file_name
[0]))
2239 return (gchar
*)file_name
;
2244 if (g_ascii_isalpha (file_name
[0]) &&
2245 file_name
[1] == ':' &&
2246 G_IS_DIR_SEPARATOR (file_name
[2]))
2247 return (gchar
*)file_name
+ 3;
2255 * @file_name: (type filename): the name of the file
2257 * Gets the name of the file without any leading directory
2258 * components. It returns a pointer into the given file name
2261 * Returns: (type filename): the name of the file without any leading
2262 * directory components
2264 * Deprecated:2.2: Use g_path_get_basename() instead, but notice
2265 * that g_path_get_basename() allocates new memory for the
2266 * returned string, unlike this function which returns a pointer
2267 * into the argument.
2270 g_basename (const gchar
*file_name
)
2274 g_return_val_if_fail (file_name
!= NULL
, NULL
);
2276 base
= strrchr (file_name
, G_DIR_SEPARATOR
);
2281 q
= strrchr (file_name
, '/');
2282 if (base
== NULL
|| (q
!= NULL
&& q
> base
))
2291 if (g_ascii_isalpha (file_name
[0]) && file_name
[1] == ':')
2292 return (gchar
*) file_name
+ 2;
2295 return (gchar
*) file_name
;
2299 * g_path_get_basename:
2300 * @file_name: (type filename): the name of the file
2302 * Gets the last component of the filename.
2304 * If @file_name ends with a directory separator it gets the component
2305 * before the last slash. If @file_name consists only of directory
2306 * separators (and on Windows, possibly a drive letter), a single
2307 * separator is returned. If @file_name is empty, it gets ".".
2309 * Returns: (type filename): a newly allocated string containing the last
2310 * component of the filename
2313 g_path_get_basename (const gchar
*file_name
)
2316 gssize last_nonslash
;
2320 g_return_val_if_fail (file_name
!= NULL
, NULL
);
2322 if (file_name
[0] == '\0')
2323 return g_strdup (".");
2325 last_nonslash
= strlen (file_name
) - 1;
2327 while (last_nonslash
>= 0 && G_IS_DIR_SEPARATOR (file_name
[last_nonslash
]))
2330 if (last_nonslash
== -1)
2331 /* string only containing slashes */
2332 return g_strdup (G_DIR_SEPARATOR_S
);
2335 if (last_nonslash
== 1 &&
2336 g_ascii_isalpha (file_name
[0]) &&
2337 file_name
[1] == ':')
2338 /* string only containing slashes and a drive */
2339 return g_strdup (G_DIR_SEPARATOR_S
);
2341 base
= last_nonslash
;
2343 while (base
>=0 && !G_IS_DIR_SEPARATOR (file_name
[base
]))
2348 g_ascii_isalpha (file_name
[0]) &&
2349 file_name
[1] == ':')
2351 #endif /* G_OS_WIN32 */
2353 len
= last_nonslash
- base
;
2354 retval
= g_malloc (len
+ 1);
2355 memcpy (retval
, file_name
+ base
+ 1, len
);
2356 retval
[len
] = '\0';
2363 * @file_name: (type filename): the name of the file
2365 * Gets the directory components of a file name.
2367 * If the file name has no directory components "." is returned.
2368 * The returned string should be freed when no longer needed.
2370 * Returns: (type filename): the directory components of the file
2372 * Deprecated: use g_path_get_dirname() instead
2376 * g_path_get_dirname:
2377 * @file_name: (type filename): the name of the file
2379 * Gets the directory components of a file name.
2381 * If the file name has no directory components "." is returned.
2382 * The returned string should be freed when no longer needed.
2384 * Returns: (type filename): the directory components of the file
2387 g_path_get_dirname (const gchar
*file_name
)
2392 g_return_val_if_fail (file_name
!= NULL
, NULL
);
2394 base
= strrchr (file_name
, G_DIR_SEPARATOR
);
2399 q
= strrchr (file_name
, '/');
2400 if (base
== NULL
|| (q
!= NULL
&& q
> base
))
2408 if (g_ascii_isalpha (file_name
[0]) && file_name
[1] == ':')
2410 gchar drive_colon_dot
[4];
2412 drive_colon_dot
[0] = file_name
[0];
2413 drive_colon_dot
[1] = ':';
2414 drive_colon_dot
[2] = '.';
2415 drive_colon_dot
[3] = '\0';
2417 return g_strdup (drive_colon_dot
);
2420 return g_strdup (".");
2423 while (base
> file_name
&& G_IS_DIR_SEPARATOR (*base
))
2427 /* base points to the char before the last slash.
2429 * In case file_name is the root of a drive (X:\) or a child of the
2430 * root of a drive (X:\foo), include the slash.
2432 * In case file_name is the root share of an UNC path
2433 * (\\server\share), add a slash, returning \\server\share\ .
2435 * In case file_name is a direct child of a share in an UNC path
2436 * (\\server\share\foo), include the slash after the share name,
2437 * returning \\server\share\ .
2439 if (base
== file_name
+ 1 &&
2440 g_ascii_isalpha (file_name
[0]) &&
2441 file_name
[1] == ':')
2443 else if (G_IS_DIR_SEPARATOR (file_name
[0]) &&
2444 G_IS_DIR_SEPARATOR (file_name
[1]) &&
2446 !G_IS_DIR_SEPARATOR (file_name
[2]) &&
2447 base
>= file_name
+ 2)
2449 const gchar
*p
= file_name
+ 2;
2450 while (*p
&& !G_IS_DIR_SEPARATOR (*p
))
2454 len
= (guint
) strlen (file_name
) + 1;
2455 base
= g_new (gchar
, len
+ 1);
2456 strcpy (base
, file_name
);
2457 base
[len
-1] = G_DIR_SEPARATOR
;
2461 if (G_IS_DIR_SEPARATOR (*p
))
2464 while (*p
&& !G_IS_DIR_SEPARATOR (*p
))
2472 len
= (guint
) 1 + base
- file_name
;
2473 base
= g_new (gchar
, len
+ 1);
2474 memmove (base
, file_name
, len
);
2480 #if defined(MAXPATHLEN)
2481 #define G_PATH_LENGTH MAXPATHLEN
2482 #elif defined(PATH_MAX)
2483 #define G_PATH_LENGTH PATH_MAX
2484 #elif defined(_PC_PATH_MAX)
2485 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
2487 #define G_PATH_LENGTH 2048
2491 * g_get_current_dir:
2493 * Gets the current directory.
2495 * The returned string should be freed when no longer needed.
2496 * The encoding of the returned string is system defined.
2497 * On Windows, it is always UTF-8.
2499 * Since GLib 2.40, this function will return the value of the "PWD"
2500 * environment variable if it is set and it happens to be the same as
2501 * the current directory. This can make a difference in the case that
2502 * the current directory is the target of a symbolic link.
2504 * Returns: (type filename): the current directory
2507 g_get_current_dir (void)
2512 wchar_t dummy
[2], *wdir
;
2515 len
= GetCurrentDirectoryW (2, dummy
);
2516 wdir
= g_new (wchar_t, len
);
2518 if (GetCurrentDirectoryW (len
, wdir
) == len
- 1)
2519 dir
= g_utf16_to_utf8 (wdir
, -1, NULL
, NULL
, NULL
);
2524 dir
= g_strdup ("\\");
2530 gchar
*buffer
= NULL
;
2532 static gulong max_len
= 0;
2533 struct stat pwdbuf
, dotbuf
;
2535 pwd
= g_getenv ("PWD");
2537 g_stat (".", &dotbuf
) == 0 && g_stat (pwd
, &pwdbuf
) == 0 &&
2538 dotbuf
.st_dev
== pwdbuf
.st_dev
&& dotbuf
.st_ino
== pwdbuf
.st_ino
)
2539 return g_strdup (pwd
);
2542 max_len
= (G_PATH_LENGTH
== -1) ? 2048 : G_PATH_LENGTH
;
2544 while (max_len
< G_MAXULONG
/ 2)
2547 buffer
= g_new (gchar
, max_len
+ 1);
2549 dir
= getcwd (buffer
, max_len
);
2551 if (dir
|| errno
!= ERANGE
)
2557 if (!dir
|| !*buffer
)
2559 /* hm, should we g_error() out here?
2560 * this can happen if e.g. "./" has mode \0000
2562 buffer
[0] = G_DIR_SEPARATOR
;
2566 dir
= g_strdup (buffer
);
2571 #endif /* !G_OS_WIN32 */
2576 /* Binary compatibility versions. Not for newly compiled code. */
2578 _GLIB_EXTERN gboolean
g_file_test_utf8 (const gchar
*filename
,
2580 _GLIB_EXTERN gboolean
g_file_get_contents_utf8 (const gchar
*filename
,
2584 _GLIB_EXTERN gint
g_mkstemp_utf8 (gchar
*tmpl
);
2585 _GLIB_EXTERN gint
g_file_open_tmp_utf8 (const gchar
*tmpl
,
2588 _GLIB_EXTERN gchar
*g_get_current_dir_utf8 (void);
2592 g_file_test_utf8 (const gchar
*filename
,
2595 return g_file_test (filename
, test
);
2599 g_file_get_contents_utf8 (const gchar
*filename
,
2604 return g_file_get_contents (filename
, contents
, length
, error
);
2608 g_mkstemp_utf8 (gchar
*tmpl
)
2610 return g_mkstemp (tmpl
);
2614 g_file_open_tmp_utf8 (const gchar
*tmpl
,
2618 return g_file_open_tmp (tmpl
, name_used
, error
);
2622 g_get_current_dir_utf8 (void)
2624 return g_get_current_dir ();