1 /* gfileutils.c - File utility functions
3 * Copyright 2000 Red Hat, Inc.
5 * GLib is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU Lesser General Public License as
7 * published by the Free Software Foundation; either version 2 of the
8 * License, or (at your option) any later version.
10 * GLib is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with GLib; see the file COPYING.LIB. If not,
17 * see <http://www.gnu.org/licenses/>.
21 #include "glibconfig.h"
29 #include <sys/types.h>
40 #endif /* G_OS_WIN32 */
50 #include "gfileutils.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 * There is a group of functions which wrap the common POSIX functions
67 * dealing with filenames (g_open(), g_rename(), g_mkdir(), g_stat(),
68 * g_unlink(), g_remove(), g_fopen(), g_freopen()). The point of these
69 * wrappers is to make it possible to handle file names with any Unicode
70 * characters in them on Windows without having to use ifdefs and the
71 * wide character API in the application code.
73 * The pathname argument should be in the GLib file name encoding.
74 * On POSIX this is the actual on-disk encoding which might correspond
75 * to the locale settings of the process (or the
76 * <envar>G_FILENAME_ENCODING</envar> environment variable), or not.
78 * On Windows the GLib file name encoding is UTF-8. Note that the
79 * Microsoft C library does not use UTF-8, but has separate APIs for
80 * current system code page and wide characters (UTF-16). The GLib
81 * wrappers call the wide character API if present (on modern Windows
82 * systems), otherwise convert to/from the system code page.
84 * Another group of functions allows to open and read directories
85 * in the GLib file name encoding. These are g_dir_open(),
86 * g_dir_read_name(), g_dir_rewind(), g_dir_close().
91 * @G_FILE_ERROR_EXIST: Operation not permitted; only the owner of
92 * the file (or other resource) or processes with special privileges
93 * can perform the operation.
94 * @G_FILE_ERROR_ISDIR: File is a directory; you cannot open a directory
95 * for writing, or create or remove hard links to it.
96 * @G_FILE_ERROR_ACCES: Permission denied; the file permissions do not
97 * allow the attempted operation.
98 * @G_FILE_ERROR_NAMETOOLONG: Filename too long.
99 * @G_FILE_ERROR_NOENT: No such file or directory. This is a "file
100 * doesn't exist" error for ordinary files that are referenced in
101 * contexts where they are expected to already exist.
102 * @G_FILE_ERROR_NOTDIR: A file that isn't a directory was specified when
103 * a directory is required.
104 * @G_FILE_ERROR_NXIO: No such device or address. The system tried to
105 * use the device represented by a file you specified, and it
106 * couldn't find the device. This can mean that the device file was
107 * installed incorrectly, or that the physical device is missing or
108 * not correctly attached to the computer.
109 * @G_FILE_ERROR_NODEV: The underlying file system of the specified file
110 * does not support memory mapping.
111 * @G_FILE_ERROR_ROFS: The directory containing the new link can't be
112 * modified because it's on a read-only file system.
113 * @G_FILE_ERROR_TXTBSY: Text file busy.
114 * @G_FILE_ERROR_FAULT: You passed in a pointer to bad memory.
115 * (GLib won't reliably return this, don't pass in pointers to bad
117 * @G_FILE_ERROR_LOOP: Too many levels of symbolic links were encountered
118 * in looking up a file name. This often indicates a cycle of symbolic
120 * @G_FILE_ERROR_NOSPC: No space left on device; write operation on a
121 * file failed because the disk is full.
122 * @G_FILE_ERROR_NOMEM: No memory available. The system cannot allocate
123 * more virtual memory because its capacity is full.
124 * @G_FILE_ERROR_MFILE: The current process has too many files open and
125 * can't open any more. Duplicate descriptors do count toward this
127 * @G_FILE_ERROR_NFILE: There are too many distinct file openings in the
129 * @G_FILE_ERROR_BADF: Bad file descriptor; for example, I/O on a
130 * descriptor that has been closed or reading from a descriptor open
131 * only for writing (or vice versa).
132 * @G_FILE_ERROR_INVAL: Invalid argument. This is used to indicate
133 * various kinds of problems with passing the wrong argument to a
135 * @G_FILE_ERROR_PIPE: Broken pipe; there is no process reading from the
136 * other end of a pipe. Every library function that returns this
137 * error code also generates a 'SIGPIPE' signal; this signal
138 * terminates the program if not handled or blocked. Thus, your
139 * program will never actually see this code unless it has handled
140 * or blocked 'SIGPIPE'.
141 * @G_FILE_ERROR_AGAIN: Resource temporarily unavailable; the call might
142 * work if you try again later.
143 * @G_FILE_ERROR_INTR: Interrupted function call; an asynchronous signal
144 * occurred and prevented completion of the call. When this
145 * happens, you should try the call again.
146 * @G_FILE_ERROR_IO: Input/output error; usually used for physical read
147 * or write errors. i.e. the disk or other physical device hardware
148 * is returning errors.
149 * @G_FILE_ERROR_PERM: Operation not permitted; only the owner of the
150 * file (or other resource) or processes with special privileges can
151 * perform the operation.
152 * @G_FILE_ERROR_NOSYS: Function not implemented; this indicates that
153 * the system is missing some functionality.
154 * @G_FILE_ERROR_FAILED: Does not correspond to a UNIX error code; this
155 * is the standard "failed for unspecified reason" error code present
156 * in all #GError error code enumerations. Returned if no specific
159 * Values corresponding to @errno codes returned from file operations
160 * on UNIX. Unlike @errno codes, GFileError values are available on
161 * all systems, even Windows. The exact meaning of each code depends
162 * on what sort of file operation you were performing; the UNIX
163 * documentation gives more details. The following error code descriptions
164 * come from the GNU C Library manual, and are under the copyright
167 * It's not very portable to make detailed assumptions about exactly
168 * which errors will be returned from a given operation. Some errors
169 * don't occur on some systems, etc., sometimes there are subtle
170 * differences in when a system will report a given error, etc.
176 * Error domain for file operations. Errors in this domain will
177 * be from the #GFileError enumeration. See #GError for information
183 * @G_FILE_TEST_IS_REGULAR: %TRUE if the file is a regular file
184 * (not a directory). Note that this test will also return %TRUE
185 * if the tested file is a symlink to a regular file.
186 * @G_FILE_TEST_IS_SYMLINK: %TRUE if the file is a symlink.
187 * @G_FILE_TEST_IS_DIR: %TRUE if the file is a directory.
188 * @G_FILE_TEST_IS_EXECUTABLE: %TRUE if the file is executable.
189 * @G_FILE_TEST_EXISTS: %TRUE if the file exists. It may or may not
192 * A test to perform on a file using g_file_test().
196 * g_mkdir_with_parents:
197 * @pathname: a pathname in the GLib file name encoding
198 * @mode: permissions to use for newly created directories
200 * Create a directory if it doesn't already exist. Create intermediate
201 * parent directories as needed, too.
203 * Returns: 0 if the directory already exists, or was successfully
204 * created. Returns -1 if an error occurred, with errno set.
209 g_mkdir_with_parents (const gchar *pathname,
214 if (pathname == NULL || *pathname == '\0')
220 fn = g_strdup (pathname);
222 if (g_path_is_absolute (fn))
223 p = (gchar *) g_path_skip_root (fn);
229 while (*p && !G_IS_DIR_SEPARATOR (*p))
237 if (!g_file_test (fn, G_FILE_TEST_EXISTS))
239 if (g_mkdir (fn, mode) == -1 && errno != EEXIST)
241 int errno_save = errno;
247 else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
255 *p++ = G_DIR_SEPARATOR;
256 while (*p && G_IS_DIR_SEPARATOR (*p))
269 * @filename: a filename to test in the GLib file name encoding
270 * @test: bitfield of #GFileTest flags
272 * Returns %TRUE if any of the tests in the bitfield @test are
273 * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS |
274 * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists;
275 * the check whether it's a directory doesn't matter since the existence
276 * test is %TRUE. With the current set of available tests, there's no point
277 * passing in more than one test at a time.
279 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
280 * so for a symbolic link to a regular file g_file_test() will return
281 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
283 * Note, that for a dangling symbolic link g_file_test() will return
284 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
286 * You should never use g_file_test() to test whether it is safe
287 * to perform an operation, because there is always the possibility
288 * of the condition changing before you actually perform the operation.
289 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
290 * to know whether it is safe to write to a file without being
291 * tricked into writing into a different location. It doesn't work!
293 * /* DON'T DO THIS */
294 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
296 * fd = g_open (filename, O_WRONLY);
297 * /* write to fd */
301 * Another thing to note is that %G_FILE_TEST_EXISTS and
302 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
303 * system call. This usually doesn't matter, but if your program
304 * is setuid or setgid it means that these tests will give you
305 * the answer for the real user ID and group ID, rather than the
306 * effective user ID and group ID.
308 * On Windows, there are no symlinks, so testing for
309 * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
310 * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
311 * its name indicates that it is executable, checking for well-known
312 * extensions and those listed in the <envar>PATHEXT</envar> environment variable.
314 * Return value: whether a test was %TRUE
317 g_file_test (const gchar *filename,
321 /* stuff missing in std vc6 api */
322 # ifndef INVALID_FILE_ATTRIBUTES
323 # define INVALID_FILE_ATTRIBUTES -1
325 # ifndef FILE_ATTRIBUTE_DEVICE
326 # define FILE_ATTRIBUTE_DEVICE 64
329 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
331 if (wfilename == NULL)
334 attributes = GetFileAttributesW (wfilename);
338 if (attributes == INVALID_FILE_ATTRIBUTES)
341 if (test & G_FILE_TEST_EXISTS)
344 if (test & G_FILE_TEST_IS_REGULAR)
346 if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0)
350 if (test & G_FILE_TEST_IS_DIR)
352 if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
356 /* "while" so that we can exit this "loop" with a simple "break" */
357 while (test & G_FILE_TEST_IS_EXECUTABLE)
359 const gchar *lastdot = strrchr (filename, '.');
360 const gchar *pathext = NULL, *p;
366 if (_stricmp (lastdot, ".exe") == 0 ||
367 _stricmp (lastdot, ".cmd") == 0 ||
368 _stricmp (lastdot, ".bat") == 0 ||
369 _stricmp (lastdot, ".com") == 0)
372 /* Check if it is one of the types listed in %PATHEXT% */
374 pathext = g_getenv ("PATHEXT");
378 pathext = g_utf8_casefold (pathext, -1);
380 lastdot = g_utf8_casefold (lastdot, -1);
381 extlen = strlen (lastdot);
386 const gchar *q = strchr (p, ';');
389 if (extlen == q - p &&
390 memcmp (lastdot, p, extlen) == 0)
392 g_free ((gchar *) pathext);
393 g_free ((gchar *) lastdot);
402 g_free ((gchar *) pathext);
403 g_free ((gchar *) lastdot);
409 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
412 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
417 /* For root, on some POSIX systems, access (filename, X_OK)
418 * will succeed even if no executable bits are set on the
419 * file. We fall through to a stat test to avoid that.
423 test &= ~G_FILE_TEST_IS_EXECUTABLE;
425 if (test & G_FILE_TEST_IS_SYMLINK)
429 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
433 if (test & (G_FILE_TEST_IS_REGULAR |
435 G_FILE_TEST_IS_EXECUTABLE))
439 if (stat (filename, &s) == 0)
441 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
444 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
447 /* The extra test for root when access (file, X_OK) succeeds.
449 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
450 ((s.st_mode & S_IXOTH) ||
451 (s.st_mode & S_IXUSR) ||
452 (s.st_mode & S_IXGRP)))
461 G_DEFINE_QUARK (g-file-error-quark, g_file_error)
464 * g_file_error_from_errno:
465 * @err_no: an "errno" value
467 * Gets a #GFileError constant based on the passed-in @err_no.
468 * For example, if you pass in <literal>EEXIST</literal> this function returns
469 * #G_FILE_ERROR_EXIST. Unlike <literal>errno</literal> values, you can portably
470 * assume that all #GFileError values will exist.
472 * Normally a #GFileError value goes into a #GError returned
473 * from a function that manipulates files. So you would use
474 * g_file_error_from_errno() when constructing a #GError.
476 * Return value: #GFileError corresponding to the given @errno
479 g_file_error_from_errno (gint err_no)
485 return G_FILE_ERROR_EXIST;
490 return G_FILE_ERROR_ISDIR;
495 return G_FILE_ERROR_ACCES;
500 return G_FILE_ERROR_NAMETOOLONG;
505 return G_FILE_ERROR_NOENT;
510 return G_FILE_ERROR_NOTDIR;
515 return G_FILE_ERROR_NXIO;
520 return G_FILE_ERROR_NODEV;
525 return G_FILE_ERROR_ROFS;
530 return G_FILE_ERROR_TXTBSY;
535 return G_FILE_ERROR_FAULT;
540 return G_FILE_ERROR_LOOP;
545 return G_FILE_ERROR_NOSPC;
550 return G_FILE_ERROR_NOMEM;
555 return G_FILE_ERROR_MFILE;
560 return G_FILE_ERROR_NFILE;
565 return G_FILE_ERROR_BADF;
570 return G_FILE_ERROR_INVAL;
575 return G_FILE_ERROR_PIPE;
580 return G_FILE_ERROR_AGAIN;
585 return G_FILE_ERROR_INTR;
590 return G_FILE_ERROR_IO;
595 return G_FILE_ERROR_PERM;
600 return G_FILE_ERROR_NOSYS;
604 return G_FILE_ERROR_FAILED;
609 format_error_message (const gchar *filename,
610 const gchar *format_string) G_GNUC_FORMAT(2);
612 #pragma GCC diagnostic push
613 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
616 format_error_message (const gchar *filename,
617 const gchar *format_string)
619 gint saved_errno = errno;
623 display_name = g_filename_display_name (filename);
624 msg = g_strdup_printf (format_string, display_name, g_strerror (saved_errno));
625 g_free (display_name);
630 #pragma GCC diagnostic pop
632 /* format string must have two '%s':
634 * - the place for the filename
635 * - the place for the strerror
638 set_file_error (GError **error,
639 const gchar *filename,
640 const gchar *format_string)
642 int saved_errno = errno;
643 char *msg = format_error_message (filename, format_string);
645 g_set_error_literal (error, G_FILE_ERROR, g_file_error_from_errno (saved_errno),
651 get_contents_stdio (const gchar *filename,
658 gsize bytes; /* always <= sizeof(buf) */
660 gsize total_bytes = 0;
661 gsize total_allocated = 0;
663 gchar *display_filename;
665 g_assert (f != NULL);
671 bytes = fread (buf, 1, sizeof (buf), f);
674 if (total_bytes > G_MAXSIZE - bytes)
677 /* Possibility of overflow eliminated above. */
678 while (total_bytes + bytes >= total_allocated)
682 if (total_allocated > G_MAXSIZE / 2)
684 total_allocated *= 2;
688 total_allocated = MIN (bytes + 1, sizeof (buf));
691 tmp = g_try_realloc (str, total_allocated);
695 display_filename = g_filename_display_name (filename);
699 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),
700 (gulong) total_allocated,
702 g_free (display_filename);
712 display_filename = g_filename_display_name (filename);
715 g_file_error_from_errno (save_errno),
716 _("Error reading file '%s': %s"),
718 g_strerror (save_errno));
719 g_free (display_filename);
724 g_assert (str != NULL);
725 memcpy (str + total_bytes, buf, bytes);
727 total_bytes += bytes;
732 if (total_allocated == 0)
734 str = g_new (gchar, 1);
738 str[total_bytes] = '\0';
741 *length = total_bytes;
748 display_filename = g_filename_display_name (filename);
752 _("File \"%s\" is too large"),
754 g_free (display_filename);
767 get_contents_regfile (const gchar *filename,
768 struct stat *stat_buf,
778 gchar *display_filename;
780 size = stat_buf->st_size;
782 alloc_size = size + 1;
783 buf = g_try_malloc (alloc_size);
787 display_filename = g_filename_display_name (filename);
791 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),
794 g_free (display_filename);
799 while (bytes_read < size)
803 rc = read (fd, buf + bytes_read, size - bytes_read);
809 int save_errno = errno;
812 display_filename = g_filename_display_name (filename);
815 g_file_error_from_errno (save_errno),
816 _("Failed to read from file '%s': %s"),
818 g_strerror (save_errno));
819 g_free (display_filename);
829 buf[bytes_read] = '\0';
832 *length = bytes_read;
848 get_contents_posix (const gchar *filename,
853 struct stat stat_buf;
856 /* O_BINARY useful on Cygwin */
857 fd = open (filename, O_RDONLY|O_BINARY);
861 set_file_error (error,
863 _("Failed to open file '%s': %s"));
868 /* I don't think this will ever fail, aside from ENOMEM, but. */
869 if (fstat (fd, &stat_buf) < 0)
871 set_file_error (error,
873 _("Failed to get attributes of file '%s': fstat() failed: %s"));
879 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
881 gboolean retval = get_contents_regfile (filename,
895 f = fdopen (fd, "r");
899 set_file_error (error,
901 _("Failed to open file '%s': fdopen() failed: %s"));
906 retval = get_contents_stdio (filename, f, contents, length, error);
912 #else /* G_OS_WIN32 */
915 get_contents_win32 (const gchar *filename,
923 f = g_fopen (filename, "rb");
927 set_file_error (error,
929 _("Failed to open file '%s': %s"));
934 retval = get_contents_stdio (filename, f, contents, length, error);
942 * g_file_get_contents:
943 * @filename: (type filename): name of a file to read contents from, in the GLib file name encoding
944 * @contents: (out) (array length=length) (element-type guint8): location to store an allocated string, use g_free() to free
945 * the returned string
946 * @length: (allow-none): location to store length in bytes of the contents, or %NULL
947 * @error: return location for a #GError, or %NULL
949 * Reads an entire file into allocated memory, with good error
952 * If the call was successful, it returns %TRUE and sets @contents to the file
953 * contents and @length to the length of the file contents in bytes. The string
954 * stored in @contents will be nul-terminated, so for text files you can pass
955 * %NULL for the @length argument. If the call was not successful, it returns
956 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
957 * codes are those in the #GFileError enumeration. In the error case,
958 * @contents is set to %NULL and @length is set to zero.
960 * Return value: %TRUE on success, %FALSE if an error occurred
963 g_file_get_contents (const gchar *filename,
968 g_return_val_if_fail (filename != NULL, FALSE);
969 g_return_val_if_fail (contents != NULL, FALSE);
976 return get_contents_win32 (filename, contents, length, error);
978 return get_contents_posix (filename, contents, length, error);
983 rename_file (const char *old_name,
984 const char *new_name,
988 if (g_rename (old_name, new_name) == -1)
990 int save_errno = errno;
991 gchar *display_old_name = g_filename_display_name (old_name);
992 gchar *display_new_name = g_filename_display_name (new_name);
996 g_file_error_from_errno (save_errno),
997 _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
1000 g_strerror (save_errno));
1002 g_free (display_old_name);
1003 g_free (display_new_name);
1012 write_to_temp_file (const gchar *contents,
1014 const gchar *dest_file,
1023 tmp_name = g_strdup_printf ("%s.XXXXXX", dest_file);
1026 fd = g_mkstemp_full (tmp_name, O_RDWR | O_BINARY, 0666);
1030 set_file_error (err, tmp_name, _("Failed to create file '%s': %s"));
1034 #ifdef HAVE_FALLOCATE
1037 /* We do this on a 'best effort' basis... It may not be supported
1038 * on the underlying filesystem.
1040 (void) fallocate (fd, 0, 0, length);
1047 s = write (fd, contents, length);
1054 set_file_error (err, tmp_name, _("Failed to write file '%s': write() failed: %s"));
1056 g_unlink (tmp_name);
1061 g_assert (s <= length);
1067 #ifdef BTRFS_SUPER_MAGIC
1071 /* On Linux, on btrfs, skip the fsync since rename-over-existing is
1072 * guaranteed to be atomic and this is the only case in which we
1073 * would fsync() anyway.
1076 if (fstatfs (fd, &buf) == 0 && buf.f_type == BTRFS_SUPER_MAGIC)
1083 struct stat statbuf;
1086 /* If the final destination exists and is > 0 bytes, we want to sync the
1087 * newly written file to ensure the data is on disk when we rename over
1088 * the destination. Otherwise if we get a system crash we can lose both
1089 * the new and the old file on some filesystems. (I.E. those that don't
1090 * guarantee the data is written to the disk before the metadata.)
1092 if (g_lstat (dest_file, &statbuf) == 0 && statbuf.st_size > 0 && fsync (fd) != 0)
1094 set_file_error (err, tmp_name, _("Failed to write file '%s': fsync() failed: %s"));
1096 g_unlink (tmp_name);
1103 #ifdef BTRFS_SUPER_MAGIC
1108 if (!g_close (fd, err))
1110 g_unlink (tmp_name);
1115 retval = g_strdup (tmp_name);
1124 * g_file_set_contents:
1125 * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1127 * @contents: (array length=length) (element-type guint8): string to write to the file
1128 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1129 * @error: return location for a #GError, or %NULL
1131 * Writes all of @contents to a file named @filename, with good error checking.
1132 * If a file called @filename already exists it will be overwritten.
1134 * This write is atomic in the sense that it is first written to a temporary
1135 * file which is then renamed to the final name. Notes:
1137 * - On UNIX, if @filename already exists hard links to @filename will break.
1138 * Also since the file is recreated, existing permissions, access control
1139 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1140 * the link itself will be replaced, not the linked file.
1142 * - On Windows renaming a file will not remove an existing file with the
1143 * new name, so on Windows there is a race condition between the existing
1144 * file being removed and the temporary file being renamed.
1146 * - On Windows there is no way to remove a file that is open to some
1147 * process, or mapped into memory. Thus, this function will fail if
1148 * @filename already exists and is open.
1150 * If the call was successful, it returns %TRUE. If the call was not successful,
1151 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1152 * Possible error codes are those in the #GFileError enumeration.
1154 * Note that the name for the temporary file is constructed by appending up
1155 * to 7 characters to @filename.
1157 * Return value: %TRUE on success, %FALSE if an error occurred
1162 g_file_set_contents (const gchar *filename,
1163 const gchar *contents,
1167 gchar *tmp_filename;
1169 GError *rename_error = NULL;
1171 g_return_val_if_fail (filename != NULL, FALSE);
1172 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1173 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1174 g_return_val_if_fail (length >= -1, FALSE);
1177 length = strlen (contents);
1179 tmp_filename = write_to_temp_file (contents, length, filename, error);
1187 if (!rename_file (tmp_filename, filename, &rename_error))
1191 g_unlink (tmp_filename);
1192 g_propagate_error (error, rename_error);
1196 #else /* G_OS_WIN32 */
1198 /* Renaming failed, but on Windows this may just mean
1199 * the file already exists. So if the target file
1200 * exists, try deleting it and do the rename again.
1202 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1204 g_unlink (tmp_filename);
1205 g_propagate_error (error, rename_error);
1210 g_error_free (rename_error);
1212 if (g_unlink (filename) == -1)
1214 set_file_error (error,
1216 _("Existing file '%s' could not be removed: g_unlink() failed: %s"));
1217 g_unlink (tmp_filename);
1222 if (!rename_file (tmp_filename, filename, error))
1224 g_unlink (tmp_filename);
1235 g_free (tmp_filename);
1240 * get_tmp_file based on the mkstemp implementation from the GNU C library.
1241 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1243 typedef gint (*GTmpFileCallback) (const gchar *, gint, gint);
1246 get_tmp_file (gchar *tmpl,
1253 static const char letters[] =
1254 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1255 static const int NLETTERS = sizeof (letters) - 1;
1258 static int counter = 0;
1260 g_return_val_if_fail (tmpl != NULL, -1);
1262 /* find the last occurrence of "XXXXXX" */
1263 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1265 if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1271 /* Get some more or less random data. */
1272 g_get_current_time (&tv);
1273 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1275 for (count = 0; count < 100; value += 7777, ++count)
1279 /* Fill in the random bits. */
1280 XXXXXX[0] = letters[v % NLETTERS];
1282 XXXXXX[1] = letters[v % NLETTERS];
1284 XXXXXX[2] = letters[v % NLETTERS];
1286 XXXXXX[3] = letters[v % NLETTERS];
1288 XXXXXX[4] = letters[v % NLETTERS];
1290 XXXXXX[5] = letters[v % NLETTERS];
1292 fd = f (tmpl, flags, mode);
1296 else if (errno != EEXIST)
1297 /* Any other error will apply also to other names we might
1298 * try, and there are 2^32 or so of them, so give up now.
1303 /* We got out of the loop because we ran out of combinations to try. */
1308 /* Some GTmpFileCallback implementations.
1310 * Note: we cannot use open() or g_open() directly because even though
1311 * they appear compatible, they may be vararg functions and calling
1312 * varargs functions through a non-varargs type is undefined.
1315 wrap_g_mkdir (const gchar *filename,
1316 int flags G_GNUC_UNUSED,
1319 /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1320 return g_mkdir (filename, mode);
1324 wrap_g_open (const gchar *filename,
1328 return g_open (filename, flags, mode);
1333 * @tmpl: (type filename): template directory name
1334 * @mode: permissions to create the temporary directory with
1336 * Creates a temporary directory. See the mkdtemp() documentation
1337 * on most UNIX-like systems.
1339 * The parameter is a string that should follow the rules for
1340 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1341 * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1342 * sequence does not have to occur at the very end of the template
1343 * and you can pass a @mode. The X string will be modified to form
1344 * the name of a directory that didn't exist. The string should be
1345 * in the GLib file name encoding. Most importantly, on Windows it
1346 * should be in UTF-8.
1348 * Return value: A pointer to @tmpl, which has been modified
1349 * to hold the directory name. In case of errors, %NULL is
1350 * returned, and %errno will be set.
1355 g_mkdtemp_full (gchar *tmpl,
1358 if (get_tmp_file (tmpl, wrap_g_mkdir, 0, mode) == -1)
1366 * @tmpl: (type filename): template directory name
1368 * Creates a temporary directory. See the mkdtemp() documentation
1369 * on most UNIX-like systems.
1371 * The parameter is a string that should follow the rules for
1372 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1373 * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1374 * sequence does not have to occur at the very end of the template
1375 * and you can pass a @mode and additional @flags. The X string will
1376 * be modified to form the name of a directory that didn't exist.
1377 * The string should be in the GLib file name encoding. Most importantly,
1378 * on Windows it should be in UTF-8.
1380 * Return value: A pointer to @tmpl, which has been modified
1381 * to hold the directory name. In case of errors, %NULL is
1382 * returned and %errno will be set.
1387 g_mkdtemp (gchar *tmpl)
1389 return g_mkdtemp_full (tmpl, 0700);
1394 * @tmpl: (type filename): template filename
1395 * @flags: flags to pass to an open() call in addition to O_EXCL
1396 * and O_CREAT, which are passed automatically
1397 * @mode: permissions to create the temporary file with
1399 * Opens a temporary file. See the mkstemp() documentation
1400 * on most UNIX-like systems.
1402 * The parameter is a string that should follow the rules for
1403 * mkstemp() templates, i.e. contain the string "XXXXXX".
1404 * g_mkstemp_full() is slightly more flexible than mkstemp()
1405 * in that the sequence does not have to occur at the very end of the
1406 * template and you can pass a @mode and additional @flags. The X
1407 * string will be modified to form the name of a file that didn't exist.
1408 * The string should be in the GLib file name encoding. Most importantly,
1409 * on Windows it should be in UTF-8.
1411 * Return value: A file handle (as from open()) to the file
1412 * opened for reading and writing. The file handle should be
1413 * closed with close(). In case of errors, -1 is returned
1414 * and %errno will be set.
1419 g_mkstemp_full (gchar *tmpl,
1423 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1424 return get_tmp_file (tmpl, wrap_g_open,
1425 flags | O_CREAT | O_EXCL, mode);
1430 * @tmpl: (type filename): template filename
1432 * Opens a temporary file. See the mkstemp() documentation
1433 * on most UNIX-like systems.
1435 * The parameter is a string that should follow the rules for
1436 * mkstemp() templates, i.e. contain the string "XXXXXX".
1437 * g_mkstemp() is slightly more flexible than mkstemp() in that the
1438 * sequence does not have to occur at the very end of the template.
1439 * The X string will be modified to form the name of a file that
1440 * didn't exist. The string should be in the GLib file name encoding.
1441 * Most importantly, on Windows it should be in UTF-8.
1443 * Return value: A file handle (as from open()) to the file
1444 * opened for reading and writing. The file is opened in binary
1445 * mode on platforms where there is a difference. The file handle
1446 * should be closed with close(). In case of errors, -1 is
1447 * returned and %errno will be set.
1450 g_mkstemp (gchar *tmpl)
1452 return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1456 g_get_tmp_name (const gchar *tmpl,
1472 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1474 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1478 gchar *display_tmpl = g_filename_display_name (tmpl);
1485 G_FILE_ERROR_FAILED,
1486 _("Template '%s' invalid, should not contain a '%s'"),
1488 g_free (display_tmpl);
1493 if (strstr (tmpl, "XXXXXX") == NULL)
1495 gchar *display_tmpl = g_filename_display_name (tmpl);
1498 G_FILE_ERROR_FAILED,
1499 _("Template '%s' doesn't contain XXXXXX"),
1501 g_free (display_tmpl);
1505 tmpdir = g_get_tmp_dir ();
1507 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1510 sep = G_DIR_SEPARATOR_S;
1512 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1514 retval = get_tmp_file (fulltemplate, f, flags, mode);
1517 set_file_error (error,
1519 _("Failed to create file '%s': %s"));
1520 g_free (fulltemplate);
1524 *name_used = fulltemplate;
1531 * @tmpl: (type filename) (allow-none): Template for file name, as in
1532 * g_mkstemp(), basename only, or %NULL for a default template
1533 * @name_used: (out) (type filename): location to store actual name used,
1535 * @error: return location for a #GError
1537 * Opens a file for writing in the preferred directory for temporary
1538 * files (as returned by g_get_tmp_dir()).
1540 * @tmpl should be a string in the GLib file name encoding containing
1541 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1542 * However, unlike these functions, the template should only be a
1543 * basename, no directory components are allowed. If template is
1544 * %NULL, a default template is used.
1546 * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
1547 * modified, and might thus be a read-only literal string.
1549 * Upon success, and if @name_used is non-%NULL, the actual name used
1550 * is returned in @name_used. This string should be freed with g_free()
1551 * when not needed any longer. The returned name is in the GLib file
1554 * Return value: A file handle (as from open()) to the file opened for
1555 * reading and writing. The file is opened in binary mode on platforms
1556 * where there is a difference. The file handle should be closed with
1557 * close(). In case of errors, -1 is returned and @error will be set.
1560 g_file_open_tmp (const gchar *tmpl,
1564 gchar *fulltemplate;
1567 result = g_get_tmp_name (tmpl, &fulltemplate,
1569 O_CREAT | O_EXCL | O_RDWR | O_BINARY,
1575 *name_used = fulltemplate;
1577 g_free (fulltemplate);
1585 * @tmpl: (type filename) (allow-none): Template for directory name,
1586 * as in g_mkdtemp(), basename only, or %NULL for a default template
1587 * @error: return location for a #GError
1589 * Creates a subdirectory in the preferred directory for temporary
1590 * files (as returned by g_get_tmp_dir()).
1592 * @tmpl should be a string in the GLib file name encoding containing
1593 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1594 * However, unlike these functions, the template should only be a
1595 * basename, no directory components are allowed. If template is
1596 * %NULL, a default template is used.
1598 * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
1599 * modified, and might thus be a read-only literal string.
1601 * Return value: (type filename): The actual name used. This string
1602 * should be freed with g_free() when not needed any longer and is
1603 * is in the GLib file name encoding. In case of errors, %NULL is
1604 * returned and @error will be set.
1609 g_dir_make_tmp (const gchar *tmpl,
1612 gchar *fulltemplate;
1614 if (g_get_tmp_name (tmpl, &fulltemplate, wrap_g_mkdir, 0, 0700, error) == -1)
1617 return fulltemplate;
1621 g_build_path_va (const gchar *separator,
1622 const gchar *first_element,
1627 gint separator_len = strlen (separator);
1628 gboolean is_first = TRUE;
1629 gboolean have_leading = FALSE;
1630 const gchar *single_element = NULL;
1631 const gchar *next_element;
1632 const gchar *last_trailing = NULL;
1635 result = g_string_new (NULL);
1638 next_element = str_array[i++];
1640 next_element = first_element;
1644 const gchar *element;
1650 element = next_element;
1652 next_element = str_array[i++];
1654 next_element = va_arg (*args, gchar *);
1659 /* Ignore empty elements */
1667 while (strncmp (start, separator, separator_len) == 0)
1668 start += separator_len;
1671 end = start + strlen (start);
1675 while (end >= start + separator_len &&
1676 strncmp (end - separator_len, separator, separator_len) == 0)
1677 end -= separator_len;
1679 last_trailing = end;
1680 while (last_trailing >= element + separator_len &&
1681 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1682 last_trailing -= separator_len;
1686 /* If the leading and trailing separator strings are in the
1687 * same element and overlap, the result is exactly that element
1689 if (last_trailing <= start)
1690 single_element = element;
1692 g_string_append_len (result, element, start - element);
1693 have_leading = TRUE;
1696 single_element = NULL;
1703 g_string_append (result, separator);
1705 g_string_append_len (result, start, end - start);
1711 g_string_free (result, TRUE);
1712 return g_strdup (single_element);
1717 g_string_append (result, last_trailing);
1719 return g_string_free (result, FALSE);
1725 * @separator: a string used to separator the elements of the path.
1726 * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
1728 * Behaves exactly like g_build_path(), but takes the path elements
1729 * as a string array, instead of varargs. This function is mainly
1730 * meant for language bindings.
1732 * Return value: a newly-allocated string that must be freed with g_free().
1737 g_build_pathv (const gchar *separator,
1743 return g_build_path_va (separator, NULL, NULL, args);
1749 * @separator: a string used to separator the elements of the path.
1750 * @first_element: the first element in the path
1751 * @...: remaining elements in path, terminated by %NULL
1753 * Creates a path from a series of elements using @separator as the
1754 * separator between elements. At the boundary between two elements,
1755 * any trailing occurrences of separator in the first element, or
1756 * leading occurrences of separator in the second element are removed
1757 * and exactly one copy of the separator is inserted.
1759 * Empty elements are ignored.
1761 * The number of leading copies of the separator on the result is
1762 * the same as the number of leading copies of the separator on
1763 * the first non-empty element.
1765 * The number of trailing copies of the separator on the result is
1766 * the same as the number of trailing copies of the separator on
1767 * the last non-empty element. (Determination of the number of
1768 * trailing copies is done without stripping leading copies, so
1769 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1770 * has 1 trailing copy.)
1772 * However, if there is only a single non-empty element, and there
1773 * are no characters in that element not part of the leading or
1774 * trailing separators, then the result is exactly the original value
1777 * Other than for determination of the number of leading and trailing
1778 * copies of the separator, elements consisting only of copies
1779 * of the separator are ignored.
1781 * Return value: a newly-allocated string that must be freed with g_free().
1784 g_build_path (const gchar *separator,
1785 const gchar *first_element,
1791 g_return_val_if_fail (separator != NULL, NULL);
1793 va_start (args, first_element);
1794 str = g_build_path_va (separator, first_element, &args, NULL);
1803 g_build_pathname_va (const gchar *first_element,
1807 /* Code copied from g_build_pathv(), and modified to use two
1808 * alternative single-character separators.
1811 gboolean is_first = TRUE;
1812 gboolean have_leading = FALSE;
1813 const gchar *single_element = NULL;
1814 const gchar *next_element;
1815 const gchar *last_trailing = NULL;
1816 gchar current_separator = '\\';
1819 result = g_string_new (NULL);
1822 next_element = str_array[i++];
1824 next_element = first_element;
1828 const gchar *element;
1834 element = next_element;
1836 next_element = str_array[i++];
1838 next_element = va_arg (*args, gchar *);
1843 /* Ignore empty elements */
1852 (*start == '\\' || *start == '/'))
1854 current_separator = *start;
1859 end = start + strlen (start);
1863 while (end >= start + 1 &&
1864 (end[-1] == '\\' || end[-1] == '/'))
1866 current_separator = end[-1];
1870 last_trailing = end;
1871 while (last_trailing >= element + 1 &&
1872 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1877 /* If the leading and trailing separator strings are in the
1878 * same element and overlap, the result is exactly that element
1880 if (last_trailing <= start)
1881 single_element = element;
1883 g_string_append_len (result, element, start - element);
1884 have_leading = TRUE;
1887 single_element = NULL;
1894 g_string_append_len (result, ¤t_separator, 1);
1896 g_string_append_len (result, start, end - start);
1902 g_string_free (result, TRUE);
1903 return g_strdup (single_element);
1908 g_string_append (result, last_trailing);
1910 return g_string_free (result, FALSE);
1917 * g_build_filenamev:
1918 * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
1920 * Behaves exactly like g_build_filename(), but takes the path elements
1921 * as a string array, instead of varargs. This function is mainly
1922 * meant for language bindings.
1924 * Return value: a newly-allocated string that must be freed with g_free().
1929 g_build_filenamev (gchar **args)
1934 str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1936 str = g_build_pathname_va (NULL, NULL, args);
1944 * @first_element: the first element in the path
1945 * @...: remaining elements in path, terminated by %NULL
1947 * Creates a filename from a series of elements using the correct
1948 * separator for filenames.
1950 * On Unix, this function behaves identically to <literal>g_build_path
1951 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1953 * On Windows, it takes into account that either the backslash
1954 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1955 * as separator in filenames, but otherwise behaves as on Unix. When
1956 * file pathname separators need to be inserted, the one that last
1957 * previously occurred in the parameters (reading from left to right)
1960 * No attempt is made to force the resulting filename to be an absolute
1961 * path. If the first element is a relative path, the result will
1962 * be a relative path.
1964 * Return value: a newly-allocated string that must be freed with g_free().
1967 g_build_filename (const gchar *first_element,
1973 va_start (args, first_element);
1975 str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1977 str = g_build_pathname_va (first_element, &args, NULL);
1986 * @filename: the symbolic link
1987 * @error: return location for a #GError
1989 * Reads the contents of the symbolic link @filename like the POSIX
1990 * readlink() function. The returned string is in the encoding used
1991 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1993 * Returns: A newly-allocated string with the contents of the symbolic link,
1994 * or %NULL if an error occurred.
1999 g_file_read_link (const gchar *filename,
2002 #ifdef HAVE_READLINK
2008 buffer = g_malloc (size);
2012 read_size = readlink (filename, buffer, size);
2015 set_file_error (error,
2017 _("Failed to read the symbolic link '%s': %s"));
2022 if (read_size < size)
2024 buffer[read_size] = 0;
2029 buffer = g_realloc (buffer, size);
2032 g_set_error_literal (error,
2035 _("Symbolic links not supported"));
2042 * g_path_is_absolute:
2043 * @file_name: a file name
2045 * Returns %TRUE if the given @file_name is an absolute file name.
2046 * Note that this is a somewhat vague concept on Windows.
2048 * On POSIX systems, an absolute file name is well-defined. It always
2049 * starts from the single root directory. For example "/usr/local".
2051 * On Windows, the concepts of current drive and drive-specific
2052 * current directory introduce vagueness. This function interprets as
2053 * an absolute file name one that either begins with a directory
2054 * separator such as "\Users\tml" or begins with the root on a drive,
2055 * for example "C:\Windows". The first case also includes UNC paths
2056 * such as "\\myserver\docs\foo". In all cases, either slashes or
2057 * backslashes are accepted.
2059 * Note that a file name relative to the current drive root does not
2060 * truly specify a file uniquely over time and across processes, as
2061 * the current drive is a per-process value and can be changed.
2063 * File names relative the current directory on some specific drive,
2064 * such as "D:foo/bar", are not interpreted as absolute by this
2065 * function, but they obviously are not relative to the normal current
2066 * directory as returned by getcwd() or g_get_current_dir()
2067 * either. Such paths should be avoided, or need to be handled using
2068 * Windows-specific code.
2070 * Returns: %TRUE if @file_name is absolute
2073 g_path_is_absolute (const gchar *file_name)
2075 g_return_val_if_fail (file_name != NULL, FALSE);
2077 if (G_IS_DIR_SEPARATOR (file_name[0]))
2081 /* Recognize drive letter on native Windows */
2082 if (g_ascii_isalpha (file_name[0]) &&
2083 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
2092 * @file_name: a file name
2094 * Returns a pointer into @file_name after the root component,
2095 * i.e. after the "/" in UNIX or "C:\" under Windows. If @file_name
2096 * is not an absolute path it returns %NULL.
2098 * Returns: a pointer into @file_name after the root component
2101 g_path_skip_root (const gchar *file_name)
2103 g_return_val_if_fail (file_name != NULL, NULL);
2105 #ifdef G_PLATFORM_WIN32
2106 /* Skip \\server\share or //server/share */
2107 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2108 G_IS_DIR_SEPARATOR (file_name[1]) &&
2110 !G_IS_DIR_SEPARATOR (file_name[2]))
2113 p = strchr (file_name + 2, G_DIR_SEPARATOR);
2119 q = strchr (file_name + 2, '/');
2120 if (p == NULL || (q != NULL && q < p))
2125 if (p && p > file_name + 2 && p[1])
2129 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
2132 /* Possibly skip a backslash after the share name */
2133 if (G_IS_DIR_SEPARATOR (file_name[0]))
2136 return (gchar *)file_name;
2141 /* Skip initial slashes */
2142 if (G_IS_DIR_SEPARATOR (file_name[0]))
2144 while (G_IS_DIR_SEPARATOR (file_name[0]))
2146 return (gchar *)file_name;
2151 if (g_ascii_isalpha (file_name[0]) &&
2152 file_name[1] == ':' &&
2153 G_IS_DIR_SEPARATOR (file_name[2]))
2154 return (gchar *)file_name + 3;
2162 * @file_name: the name of the file
2164 * Gets the name of the file without any leading directory
2165 * components. It returns a pointer into the given file name
2168 * Return value: the name of the file without any leading
2169 * directory components
2171 * Deprecated:2.2: Use g_path_get_basename() instead, but notice
2172 * that g_path_get_basename() allocates new memory for the
2173 * returned string, unlike this function which returns a pointer
2174 * into the argument.
2177 g_basename (const gchar *file_name)
2181 g_return_val_if_fail (file_name != NULL, NULL);
2183 base = strrchr (file_name, G_DIR_SEPARATOR);
2188 q = strrchr (file_name, '/');
2189 if (base == NULL || (q != NULL && q > base))
2198 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2199 return (gchar*) file_name + 2;
2202 return (gchar*) file_name;
2206 * g_path_get_basename:
2207 * @file_name: the name of the file
2209 * Gets the last component of the filename.
2211 * If @file_name ends with a directory separator it gets the component
2212 * before the last slash. If @file_name consists only of directory
2213 * separators (and on Windows, possibly a drive letter), a single
2214 * separator is returned. If @file_name is empty, it gets ".".
2216 * Return value: a newly allocated string containing the last
2217 * component of the filename
2220 g_path_get_basename (const gchar *file_name)
2223 gssize last_nonslash;
2227 g_return_val_if_fail (file_name != NULL, NULL);
2229 if (file_name[0] == '\0')
2230 return g_strdup (".");
2232 last_nonslash = strlen (file_name) - 1;
2234 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
2237 if (last_nonslash == -1)
2238 /* string only containing slashes */
2239 return g_strdup (G_DIR_SEPARATOR_S);
2242 if (last_nonslash == 1 &&
2243 g_ascii_isalpha (file_name[0]) &&
2244 file_name[1] == ':')
2245 /* string only containing slashes and a drive */
2246 return g_strdup (G_DIR_SEPARATOR_S);
2248 base = last_nonslash;
2250 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
2255 g_ascii_isalpha (file_name[0]) &&
2256 file_name[1] == ':')
2258 #endif /* G_OS_WIN32 */
2260 len = last_nonslash - base;
2261 retval = g_malloc (len + 1);
2262 memcpy (retval, file_name + base + 1, len);
2263 retval [len] = '\0';
2270 * @file_name: the name of the file
2272 * Gets the directory components of a file name.
2274 * If the file name has no directory components "." is returned.
2275 * The returned string should be freed when no longer needed.
2277 * Returns: the directory components of the file
2279 * Deprecated: use g_path_get_dirname() instead
2283 * g_path_get_dirname:
2284 * @file_name: the name of the file
2286 * Gets the directory components of a file name.
2288 * If the file name has no directory components "." is returned.
2289 * The returned string should be freed when no longer needed.
2291 * Returns: the directory components of the file
2294 g_path_get_dirname (const gchar *file_name)
2299 g_return_val_if_fail (file_name != NULL, NULL);
2301 base = strrchr (file_name, G_DIR_SEPARATOR);
2306 q = strrchr (file_name, '/');
2307 if (base == NULL || (q != NULL && q > base))
2315 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2317 gchar drive_colon_dot[4];
2319 drive_colon_dot[0] = file_name[0];
2320 drive_colon_dot[1] = ':';
2321 drive_colon_dot[2] = '.';
2322 drive_colon_dot[3] = '\0';
2324 return g_strdup (drive_colon_dot);
2327 return g_strdup (".");
2330 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
2334 /* base points to the char before the last slash.
2336 * In case file_name is the root of a drive (X:\) or a child of the
2337 * root of a drive (X:\foo), include the slash.
2339 * In case file_name is the root share of an UNC path
2340 * (\\server\share), add a slash, returning \\server\share\ .
2342 * In case file_name is a direct child of a share in an UNC path
2343 * (\\server\share\foo), include the slash after the share name,
2344 * returning \\server\share\ .
2346 if (base == file_name + 1 &&
2347 g_ascii_isalpha (file_name[0]) &&
2348 file_name[1] == ':')
2350 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2351 G_IS_DIR_SEPARATOR (file_name[1]) &&
2353 !G_IS_DIR_SEPARATOR (file_name[2]) &&
2354 base >= file_name + 2)
2356 const gchar *p = file_name + 2;
2357 while (*p && !G_IS_DIR_SEPARATOR (*p))
2361 len = (guint) strlen (file_name) + 1;
2362 base = g_new (gchar, len + 1);
2363 strcpy (base, file_name);
2364 base[len-1] = G_DIR_SEPARATOR;
2368 if (G_IS_DIR_SEPARATOR (*p))
2371 while (*p && !G_IS_DIR_SEPARATOR (*p))
2379 len = (guint) 1 + base - file_name;
2380 base = g_new (gchar, len + 1);
2381 memmove (base, file_name, len);
2387 #if defined(MAXPATHLEN)
2388 #define G_PATH_LENGTH MAXPATHLEN
2389 #elif defined(PATH_MAX)
2390 #define G_PATH_LENGTH PATH_MAX
2391 #elif defined(_PC_PATH_MAX)
2392 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
2394 #define G_PATH_LENGTH 2048
2398 * g_get_current_dir:
2400 * Gets the current directory.
2402 * The returned string should be freed when no longer needed.
2403 * The encoding of the returned string is system defined.
2404 * On Windows, it is always UTF-8.
2406 * Since GLib 2.40, this function will return the value of the "PWD"
2407 * environment variable if it is set and it happens to be the same as
2408 * the current directory. This can make a difference in the case that
2409 * the current directory is the target of a symbolic link.
2411 * Returns: the current directory
2414 g_get_current_dir (void)
2419 wchar_t dummy[2], *wdir;
2422 len = GetCurrentDirectoryW (2, dummy);
2423 wdir = g_new (wchar_t, len);
2425 if (GetCurrentDirectoryW (len, wdir) == len - 1)
2426 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
2431 dir = g_strdup ("\\");
2437 gchar *buffer = NULL;
2439 static gulong max_len = 0;
2440 struct stat pwdbuf, dotbuf;
2442 pwd = g_getenv ("PWD");
2444 g_stat (".", &dotbuf) == 0 && g_stat (pwd, &pwdbuf) == 0 &&
2445 dotbuf.st_dev == pwdbuf.st_dev && dotbuf.st_ino == pwdbuf.st_ino)
2446 return g_strdup (pwd);
2449 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
2451 while (max_len < G_MAXULONG / 2)
2454 buffer = g_new (gchar, max_len + 1);
2456 dir = getcwd (buffer, max_len);
2458 if (dir || errno != ERANGE)
2464 if (!dir || !*buffer)
2466 /* hm, should we g_error() out here?
2467 * this can happen if e.g. "./" has mode \0000
2469 buffer[0] = G_DIR_SEPARATOR;
2473 dir = g_strdup (buffer);
2478 #endif /* !G_OS_WIN32 */
2482 /* NOTE : Keep this part last to ensure nothing in this file uses thn
2483 * below binary compatibility versions.
2485 #if defined (G_OS_WIN32) && !defined (_WIN64)
2487 /* Binary compatibility versions. Will be called by code compiled
2488 * against quite old (pre-2.8, I think) headers only, not from more
2489 * recently compiled code.
2495 g_file_test (const gchar *filename,
2498 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
2501 if (utf8_filename == NULL)
2504 retval = g_file_test_utf8 (utf8_filename, test);
2506 g_free (utf8_filename);
2511 #undef g_file_get_contents
2514 g_file_get_contents (const gchar *filename,
2519 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
2522 if (utf8_filename == NULL)
2525 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
2527 g_free (utf8_filename);
2535 wrap_libc_open (const gchar *filename,
2539 return open (filename, flags, mode);
2543 g_mkstemp (gchar *tmpl)
2545 /* This is the backward compatibility system codepage version,
2546 * thus use normal open().
2548 return get_tmp_file (tmpl, wrap_libc_open,
2549 O_RDWR | O_CREAT | O_EXCL, 0600);
2552 #undef g_file_open_tmp
2555 g_file_open_tmp (const gchar *tmpl,
2559 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
2560 gchar *utf8_name_used;
2563 if (utf8_tmpl == NULL)
2566 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
2572 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
2574 g_free (utf8_name_used);
2579 #undef g_get_current_dir
2582 g_get_current_dir (void)
2584 gchar *utf8_dir = g_get_current_dir_utf8 ();
2585 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);