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 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 * Boston, MA 02111-1307, USA.
22 #include "glibconfig.h"
33 #include <sys/types.h>
41 #endif /* G_OS_WIN32 */
51 #include "gfileutils.h"
56 #ifdef HAVE_LINUX_MAGIC_H /* for btrfs check */
57 #include <linux/magic.h>
64 * @title: File Utilities
65 * @short_description: various file-related functions
67 * There is a group of functions which wrap the common POSIX functions
68 * dealing with filenames (g_open(), g_rename(), g_mkdir(), g_stat(),
69 * g_unlink(), g_remove(), g_fopen(), g_freopen()). The point of these
70 * wrappers is to make it possible to handle file names with any Unicode
71 * characters in them on Windows without having to use ifdefs and the
72 * wide character API in the application code.
74 * The pathname argument should be in the GLib file name encoding.
75 * On POSIX this is the actual on-disk encoding which might correspond
76 * to the locale settings of the process (or the
77 * <envar>G_FILENAME_ENCODING</envar> environment variable), or not.
79 * On Windows the GLib file name encoding is UTF-8. Note that the
80 * Microsoft C library does not use UTF-8, but has separate APIs for
81 * current system code page and wide characters (UTF-16). The GLib
82 * wrappers call the wide character API if present (on modern Windows
83 * systems), otherwise convert to/from the system code page.
85 * Another group of functions allows to open and read directories
86 * in the GLib file name encoding. These are g_dir_open(),
87 * g_dir_read_name(), g_dir_rewind(), g_dir_close().
92 * @G_FILE_ERROR_EXIST: Operation not permitted; only the owner of
93 * the file (or other resource) or processes with special privileges
94 * can perform the operation.
95 * @G_FILE_ERROR_ISDIR: File is a directory; you cannot open a directory
96 * for writing, or create or remove hard links to it.
97 * @G_FILE_ERROR_ACCES: Permission denied; the file permissions do not
98 * allow the attempted operation.
99 * @G_FILE_ERROR_NAMETOOLONG: Filename too long.
100 * @G_FILE_ERROR_NOENT: No such file or directory. This is a "file
101 * doesn't exist" error for ordinary files that are referenced in
102 * contexts where they are expected to already exist.
103 * @G_FILE_ERROR_NOTDIR: A file that isn't a directory was specified when
104 * a directory is required.
105 * @G_FILE_ERROR_NXIO: No such device or address. The system tried to
106 * use the device represented by a file you specified, and it
107 * couldn't find the device. This can mean that the device file was
108 * installed incorrectly, or that the physical device is missing or
109 * not correctly attached to the computer.
110 * @G_FILE_ERROR_NODEV: The underlying file system of the specified file
111 * does not support memory mapping.
112 * @G_FILE_ERROR_ROFS: The directory containing the new link can't be
113 * modified because it's on a read-only file system.
114 * @G_FILE_ERROR_TXTBSY: Text file busy.
115 * @G_FILE_ERROR_FAULT: You passed in a pointer to bad memory.
116 * (GLib won't reliably return this, don't pass in pointers to bad
118 * @G_FILE_ERROR_LOOP: Too many levels of symbolic links were encountered
119 * in looking up a file name. This often indicates a cycle of symbolic
121 * @G_FILE_ERROR_NOSPC: No space left on device; write operation on a
122 * file failed because the disk is full.
123 * @G_FILE_ERROR_NOMEM: No memory available. The system cannot allocate
124 * more virtual memory because its capacity is full.
125 * @G_FILE_ERROR_MFILE: The current process has too many files open and
126 * can't open any more. Duplicate descriptors do count toward this
128 * @G_FILE_ERROR_NFILE: There are too many distinct file openings in the
130 * @G_FILE_ERROR_BADF: Bad file descriptor; for example, I/O on a
131 * descriptor that has been closed or reading from a descriptor open
132 * only for writing (or vice versa).
133 * @G_FILE_ERROR_INVAL: Invalid argument. This is used to indicate
134 * various kinds of problems with passing the wrong argument to a
136 * @G_FILE_ERROR_PIPE: Broken pipe; there is no process reading from the
137 * other end of a pipe. Every library function that returns this
138 * error code also generates a 'SIGPIPE' signal; this signal
139 * terminates the program if not handled or blocked. Thus, your
140 * program will never actually see this code unless it has handled
141 * or blocked 'SIGPIPE'.
142 * @G_FILE_ERROR_AGAIN: Resource temporarily unavailable; the call might
143 * work if you try again later.
144 * @G_FILE_ERROR_INTR: Interrupted function call; an asynchronous signal
145 * occurred and prevented completion of the call. When this
146 * happens, you should try the call again.
147 * @G_FILE_ERROR_IO: Input/output error; usually used for physical read
148 * or write errors. i.e. the disk or other physical device hardware
149 * is returning errors.
150 * @G_FILE_ERROR_PERM: Operation not permitted; only the owner of the
151 * file (or other resource) or processes with special privileges can
152 * perform the operation.
153 * @G_FILE_ERROR_NOSYS: Function not implemented; this indicates that
154 * the system is missing some functionality.
155 * @G_FILE_ERROR_FAILED: Does not correspond to a UNIX error code; this
156 * is the standard "failed for unspecified reason" error code present
157 * in all #GError error code enumerations. Returned if no specific
160 * Values corresponding to @errno codes returned from file operations
161 * on UNIX. Unlike @errno codes, GFileError values are available on
162 * all systems, even Windows. The exact meaning of each code depends
163 * on what sort of file operation you were performing; the UNIX
164 * documentation gives more details. The following error code descriptions
165 * come from the GNU C Library manual, and are under the copyright
168 * It's not very portable to make detailed assumptions about exactly
169 * which errors will be returned from a given operation. Some errors
170 * don't occur on some systems, etc., sometimes there are subtle
171 * differences in when a system will report a given error, etc.
177 * Error domain for file operations. Errors in this domain will
178 * be from the #GFileError enumeration. See #GError for information
184 * @G_FILE_TEST_IS_REGULAR: %TRUE if the file is a regular file
185 * (not a directory). Note that this test will also return %TRUE
186 * if the tested file is a symlink to a regular file.
187 * @G_FILE_TEST_IS_SYMLINK: %TRUE if the file is a symlink.
188 * @G_FILE_TEST_IS_DIR: %TRUE if the file is a directory.
189 * @G_FILE_TEST_IS_EXECUTABLE: %TRUE if the file is executable.
190 * @G_FILE_TEST_EXISTS: %TRUE if the file exists. It may or may not
193 * A test to perform on a file using g_file_test().
197 * g_mkdir_with_parents:
198 * @pathname: a pathname in the GLib file name encoding
199 * @mode: permissions to use for newly created directories
201 * Create a directory if it doesn't already exist. Create intermediate
202 * parent directories as needed, too.
204 * Returns: 0 if the directory already exists, or was successfully
205 * created. Returns -1 if an error occurred, with errno set.
210 g_mkdir_with_parents (const gchar *pathname,
215 if (pathname == NULL || *pathname == '\0')
221 fn = g_strdup (pathname);
223 if (g_path_is_absolute (fn))
224 p = (gchar *) g_path_skip_root (fn);
230 while (*p && !G_IS_DIR_SEPARATOR (*p))
238 if (!g_file_test (fn, G_FILE_TEST_EXISTS))
240 if (g_mkdir (fn, mode) == -1 && errno != EEXIST)
242 int errno_save = errno;
248 else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
256 *p++ = G_DIR_SEPARATOR;
257 while (*p && G_IS_DIR_SEPARATOR (*p))
270 * @filename: a filename to test in the GLib file name encoding
271 * @test: bitfield of #GFileTest flags
273 * Returns %TRUE if any of the tests in the bitfield @test are
274 * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS |
275 * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists;
276 * the check whether it's a directory doesn't matter since the existence
277 * test is %TRUE. With the current set of available tests, there's no point
278 * passing in more than one test at a time.
280 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
281 * so for a symbolic link to a regular file g_file_test() will return
282 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
284 * Note, that for a dangling symbolic link g_file_test() will return
285 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
287 * You should never use g_file_test() to test whether it is safe
288 * to perform an operation, because there is always the possibility
289 * of the condition changing before you actually perform the operation.
290 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
291 * to know whether it is safe to write to a file without being
292 * tricked into writing into a different location. It doesn't work!
294 * /* DON'T DO THIS */
295 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
297 * fd = g_open (filename, O_WRONLY);
298 * /* write to fd */
302 * Another thing to note is that %G_FILE_TEST_EXISTS and
303 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
304 * system call. This usually doesn't matter, but if your program
305 * is setuid or setgid it means that these tests will give you
306 * the answer for the real user ID and group ID, rather than the
307 * effective user ID and group ID.
309 * On Windows, there are no symlinks, so testing for
310 * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
311 * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
312 * its name indicates that it is executable, checking for well-known
313 * extensions and those listed in the <envar>PATHEXT</envar> environment variable.
315 * Return value: whether a test was %TRUE
318 g_file_test (const gchar *filename,
322 /* stuff missing in std vc6 api */
323 # ifndef INVALID_FILE_ATTRIBUTES
324 # define INVALID_FILE_ATTRIBUTES -1
326 # ifndef FILE_ATTRIBUTE_DEVICE
327 # define FILE_ATTRIBUTE_DEVICE 64
330 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
332 if (wfilename == NULL)
335 attributes = GetFileAttributesW (wfilename);
339 if (attributes == INVALID_FILE_ATTRIBUTES)
342 if (test & G_FILE_TEST_EXISTS)
345 if (test & G_FILE_TEST_IS_REGULAR)
347 if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0)
351 if (test & G_FILE_TEST_IS_DIR)
353 if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
357 /* "while" so that we can exit this "loop" with a simple "break" */
358 while (test & G_FILE_TEST_IS_EXECUTABLE)
360 const gchar *lastdot = strrchr (filename, '.');
361 const gchar *pathext = NULL, *p;
367 if (_stricmp (lastdot, ".exe") == 0 ||
368 _stricmp (lastdot, ".cmd") == 0 ||
369 _stricmp (lastdot, ".bat") == 0 ||
370 _stricmp (lastdot, ".com") == 0)
373 /* Check if it is one of the types listed in %PATHEXT% */
375 pathext = g_getenv ("PATHEXT");
379 pathext = g_utf8_casefold (pathext, -1);
381 lastdot = g_utf8_casefold (lastdot, -1);
382 extlen = strlen (lastdot);
387 const gchar *q = strchr (p, ';');
390 if (extlen == q - p &&
391 memcmp (lastdot, p, extlen) == 0)
393 g_free ((gchar *) pathext);
394 g_free ((gchar *) lastdot);
403 g_free ((gchar *) pathext);
404 g_free ((gchar *) lastdot);
410 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
413 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
418 /* For root, on some POSIX systems, access (filename, X_OK)
419 * will succeed even if no executable bits are set on the
420 * file. We fall through to a stat test to avoid that.
424 test &= ~G_FILE_TEST_IS_EXECUTABLE;
426 if (test & G_FILE_TEST_IS_SYMLINK)
430 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
434 if (test & (G_FILE_TEST_IS_REGULAR |
436 G_FILE_TEST_IS_EXECUTABLE))
440 if (stat (filename, &s) == 0)
442 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
445 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
448 /* The extra test for root when access (file, X_OK) succeeds.
450 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
451 ((s.st_mode & S_IXOTH) ||
452 (s.st_mode & S_IXUSR) ||
453 (s.st_mode & S_IXGRP)))
462 G_DEFINE_QUARK (g-file-error-quark, g_file_error)
465 * g_file_error_from_errno:
466 * @err_no: an "errno" value
468 * Gets a #GFileError constant based on the passed-in @err_no.
469 * For example, if you pass in <literal>EEXIST</literal> this function returns
470 * #G_FILE_ERROR_EXIST. Unlike <literal>errno</literal> values, you can portably
471 * assume that all #GFileError values will exist.
473 * Normally a #GFileError value goes into a #GError returned
474 * from a function that manipulates files. So you would use
475 * g_file_error_from_errno() when constructing a #GError.
477 * Return value: #GFileError corresponding to the given @errno
480 g_file_error_from_errno (gint err_no)
486 return G_FILE_ERROR_EXIST;
492 return G_FILE_ERROR_ISDIR;
498 return G_FILE_ERROR_ACCES;
504 return G_FILE_ERROR_NAMETOOLONG;
510 return G_FILE_ERROR_NOENT;
516 return G_FILE_ERROR_NOTDIR;
522 return G_FILE_ERROR_NXIO;
528 return G_FILE_ERROR_NODEV;
534 return G_FILE_ERROR_ROFS;
540 return G_FILE_ERROR_TXTBSY;
546 return G_FILE_ERROR_FAULT;
552 return G_FILE_ERROR_LOOP;
558 return G_FILE_ERROR_NOSPC;
564 return G_FILE_ERROR_NOMEM;
570 return G_FILE_ERROR_MFILE;
576 return G_FILE_ERROR_NFILE;
582 return G_FILE_ERROR_BADF;
588 return G_FILE_ERROR_INVAL;
594 return G_FILE_ERROR_PIPE;
600 return G_FILE_ERROR_AGAIN;
606 return G_FILE_ERROR_INTR;
612 return G_FILE_ERROR_IO;
618 return G_FILE_ERROR_PERM;
624 return G_FILE_ERROR_NOSYS;
629 return G_FILE_ERROR_FAILED;
635 get_contents_stdio (const gchar *display_filename,
644 gsize total_bytes = 0;
645 gsize total_allocated = 0;
648 g_assert (f != NULL);
654 bytes = fread (buf, 1, sizeof (buf), f);
657 while ((total_bytes + bytes + 1) > total_allocated)
660 total_allocated *= 2;
662 total_allocated = MIN (bytes + 1, sizeof (buf));
664 tmp = g_try_realloc (str, total_allocated);
671 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),
672 (gulong) total_allocated,
685 g_file_error_from_errno (save_errno),
686 _("Error reading file '%s': %s"),
688 g_strerror (save_errno));
693 memcpy (str + total_bytes, buf, bytes);
695 if (total_bytes + bytes < total_bytes)
700 _("File \"%s\" is too large"),
706 total_bytes += bytes;
711 if (total_allocated == 0)
713 str = g_new (gchar, 1);
717 str[total_bytes] = '\0';
720 *length = total_bytes;
737 get_contents_regfile (const gchar *display_filename,
738 struct stat *stat_buf,
749 size = stat_buf->st_size;
751 alloc_size = size + 1;
752 buf = g_try_malloc (alloc_size);
759 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),
767 while (bytes_read < size)
771 rc = read (fd, buf + bytes_read, size - bytes_read);
777 int save_errno = errno;
782 g_file_error_from_errno (save_errno),
783 _("Failed to read from file '%s': %s"),
785 g_strerror (save_errno));
796 buf[bytes_read] = '\0';
799 *length = bytes_read;
815 get_contents_posix (const gchar *filename,
820 struct stat stat_buf;
822 gchar *display_filename = g_filename_display_name (filename);
824 /* O_BINARY useful on Cygwin */
825 fd = open (filename, O_RDONLY|O_BINARY);
829 int save_errno = errno;
833 g_file_error_from_errno (save_errno),
834 _("Failed to open file '%s': %s"),
836 g_strerror (save_errno));
837 g_free (display_filename);
842 /* I don't think this will ever fail, aside from ENOMEM, but. */
843 if (fstat (fd, &stat_buf) < 0)
845 int save_errno = errno;
850 g_file_error_from_errno (save_errno),
851 _("Failed to get attributes of file '%s': fstat() failed: %s"),
853 g_strerror (save_errno));
854 g_free (display_filename);
859 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
861 gboolean retval = get_contents_regfile (display_filename,
867 g_free (display_filename);
876 f = fdopen (fd, "r");
880 int save_errno = errno;
884 g_file_error_from_errno (save_errno),
885 _("Failed to open file '%s': fdopen() failed: %s"),
887 g_strerror (save_errno));
888 g_free (display_filename);
893 retval = get_contents_stdio (display_filename, f, contents, length, error);
894 g_free (display_filename);
900 #else /* G_OS_WIN32 */
903 get_contents_win32 (const gchar *filename,
910 gchar *display_filename = g_filename_display_name (filename);
913 f = g_fopen (filename, "rb");
920 g_file_error_from_errno (save_errno),
921 _("Failed to open file '%s': %s"),
923 g_strerror (save_errno));
924 g_free (display_filename);
929 retval = get_contents_stdio (display_filename, f, contents, length, error);
930 g_free (display_filename);
938 * g_file_get_contents:
939 * @filename: (type filename): name of a file to read contents from, in the GLib file name encoding
940 * @contents: (out) (array length=length) (element-type guint8): location to store an allocated string, use g_free() to free
941 * the returned string
942 * @length: (allow-none): location to store length in bytes of the contents, or %NULL
943 * @error: return location for a #GError, or %NULL
945 * Reads an entire file into allocated memory, with good error
948 * If the call was successful, it returns %TRUE and sets @contents to the file
949 * contents and @length to the length of the file contents in bytes. The string
950 * stored in @contents will be nul-terminated, so for text files you can pass
951 * %NULL for the @length argument. If the call was not successful, it returns
952 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
953 * codes are those in the #GFileError enumeration. In the error case,
954 * @contents is set to %NULL and @length is set to zero.
956 * Return value: %TRUE on success, %FALSE if an error occurred
959 g_file_get_contents (const gchar *filename,
964 g_return_val_if_fail (filename != NULL, FALSE);
965 g_return_val_if_fail (contents != NULL, FALSE);
972 return get_contents_win32 (filename, contents, length, error);
974 return get_contents_posix (filename, contents, length, error);
979 rename_file (const char *old_name,
980 const char *new_name,
984 if (g_rename (old_name, new_name) == -1)
986 int save_errno = errno;
987 gchar *display_old_name = g_filename_display_name (old_name);
988 gchar *display_new_name = g_filename_display_name (new_name);
992 g_file_error_from_errno (save_errno),
993 _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
996 g_strerror (save_errno));
998 g_free (display_old_name);
999 g_free (display_new_name);
1008 format_error_message (const gchar *filename,
1009 const gchar *format_string) G_GNUC_FORMAT(2);
1011 #pragma GCC diagnostic push
1012 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
1015 format_error_message (const gchar *filename,
1016 const gchar *format_string)
1018 gint saved_errno = errno;
1019 gchar *display_name;
1022 display_name = g_filename_display_name (filename);
1023 msg = g_strdup_printf (format_string, display_name, g_strerror (saved_errno));
1024 g_free (display_name);
1029 #pragma GCC diagnostic pop
1031 /* format string must have two '%s':
1033 * - the place for the filename
1034 * - the place for the strerror
1037 set_file_error (GError **error,
1038 const gchar *filename,
1039 const gchar *format_string)
1042 int saved_errno = errno;
1043 char *msg = format_error_message (filename, format_string);
1045 g_set_error_literal (error, G_FILE_ERROR, g_file_error_from_errno (saved_errno),
1051 write_to_temp_file (const gchar *contents,
1053 const gchar *dest_file,
1062 tmp_name = g_strdup_printf ("%s.XXXXXX", dest_file);
1065 fd = g_mkstemp_full (tmp_name, O_RDWR | O_BINARY, 0666);
1069 set_file_error (err, tmp_name, _("Failed to create file '%s': %s"));
1073 #ifdef HAVE_FALLOCATE
1076 /* We do this on a 'best effort' basis... It may not be supported
1077 * on the underlying filesystem.
1079 (void) fallocate (fd, 0, 0, length);
1086 s = write (fd, contents, length);
1093 set_file_error (err, tmp_name, _("Failed to write file '%s': write() failed: %s"));
1095 g_unlink (tmp_name);
1100 g_assert (s <= length);
1106 #ifdef BTRFS_SUPER_MAGIC
1110 /* On Linux, on btrfs, skip the fsync since rename-over-existing is
1111 * guaranteed to be atomic and this is the only case in which we
1112 * would fsync() anyway.
1115 if (fstatfs (fd, &buf) == 0 && buf.f_type == BTRFS_SUPER_MAGIC)
1122 struct stat statbuf;
1125 /* If the final destination exists and is > 0 bytes, we want to sync the
1126 * newly written file to ensure the data is on disk when we rename over
1127 * the destination. Otherwise if we get a system crash we can lose both
1128 * the new and the old file on some filesystems. (I.E. those that don't
1129 * guarantee the data is written to the disk before the metadata.)
1131 if (g_lstat (dest_file, &statbuf) == 0 && statbuf.st_size > 0 && fsync (fd) != 0)
1133 set_file_error (err, tmp_name, _("Failed to write file '%s': fsync() failed: %s"));
1135 g_unlink (tmp_name);
1142 #ifdef BTRFS_SUPER_MAGIC
1147 if (!g_close (fd, err))
1149 g_unlink (tmp_name);
1154 retval = g_strdup (tmp_name);
1163 * g_file_set_contents:
1164 * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1166 * @contents: (array length=length) (element-type guint8): string to write to the file
1167 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1168 * @error: return location for a #GError, or %NULL
1170 * Writes all of @contents to a file named @filename, with good error checking.
1171 * If a file called @filename already exists it will be overwritten.
1173 * This write is atomic in the sense that it is first written to a temporary
1174 * file which is then renamed to the final name. Notes:
1177 * On Unix, if @filename already exists hard links to @filename will break.
1178 * Also since the file is recreated, existing permissions, access control
1179 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1180 * the link itself will be replaced, not the linked file.
1183 * On Windows renaming a file will not remove an existing file with the
1184 * new name, so on Windows there is a race condition between the existing
1185 * file being removed and the temporary file being renamed.
1188 * On Windows there is no way to remove a file that is open to some
1189 * process, or mapped into memory. Thus, this function will fail if
1190 * @filename already exists and is open.
1194 * If the call was successful, it returns %TRUE. If the call was not successful,
1195 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1196 * Possible error codes are those in the #GFileError enumeration.
1198 * Note that the name for the temporary file is constructed by appending up
1199 * to 7 characters to @filename.
1201 * Return value: %TRUE on success, %FALSE if an error occurred
1206 g_file_set_contents (const gchar *filename,
1207 const gchar *contents,
1211 gchar *tmp_filename;
1213 GError *rename_error = NULL;
1215 g_return_val_if_fail (filename != NULL, FALSE);
1216 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1217 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1218 g_return_val_if_fail (length >= -1, FALSE);
1221 length = strlen (contents);
1223 tmp_filename = write_to_temp_file (contents, length, filename, error);
1231 if (!rename_file (tmp_filename, filename, &rename_error))
1235 g_unlink (tmp_filename);
1236 g_propagate_error (error, rename_error);
1240 #else /* G_OS_WIN32 */
1242 /* Renaming failed, but on Windows this may just mean
1243 * the file already exists. So if the target file
1244 * exists, try deleting it and do the rename again.
1246 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1248 g_unlink (tmp_filename);
1249 g_propagate_error (error, rename_error);
1254 g_error_free (rename_error);
1256 if (g_unlink (filename) == -1)
1258 gchar *display_filename = g_filename_display_name (filename);
1260 int save_errno = errno;
1264 g_file_error_from_errno (save_errno),
1265 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1267 g_strerror (save_errno));
1269 g_free (display_filename);
1270 g_unlink (tmp_filename);
1275 if (!rename_file (tmp_filename, filename, error))
1277 g_unlink (tmp_filename);
1288 g_free (tmp_filename);
1293 * get_tmp_file based on the mkstemp implementation from the GNU C library.
1294 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1296 typedef gint (*GTmpFileCallback) (const gchar *, gint, gint);
1299 get_tmp_file (gchar *tmpl,
1306 static const char letters[] =
1307 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1308 static const int NLETTERS = sizeof (letters) - 1;
1311 static int counter = 0;
1313 g_return_val_if_fail (tmpl != NULL, -1);
1315 /* find the last occurrence of "XXXXXX" */
1316 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1318 if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1324 /* Get some more or less random data. */
1325 g_get_current_time (&tv);
1326 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1328 for (count = 0; count < 100; value += 7777, ++count)
1332 /* Fill in the random bits. */
1333 XXXXXX[0] = letters[v % NLETTERS];
1335 XXXXXX[1] = letters[v % NLETTERS];
1337 XXXXXX[2] = letters[v % NLETTERS];
1339 XXXXXX[3] = letters[v % NLETTERS];
1341 XXXXXX[4] = letters[v % NLETTERS];
1343 XXXXXX[5] = letters[v % NLETTERS];
1345 fd = f (tmpl, flags, mode);
1349 else if (errno != EEXIST)
1350 /* Any other error will apply also to other names we might
1351 * try, and there are 2^32 or so of them, so give up now.
1356 /* We got out of the loop because we ran out of combinations to try. */
1361 /* Some GTmpFileCallback implementations.
1363 * Note: we cannot use open() or g_open() directly because even though
1364 * they appear compatible, they may be vararg functions and calling
1365 * varargs functions through a non-varargs type is undefined.
1368 wrap_g_mkdir (const gchar *filename,
1369 int flags G_GNUC_UNUSED,
1372 /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1373 return g_mkdir (filename, mode);
1377 wrap_g_open (const gchar *filename,
1381 return g_open (filename, flags, mode);
1386 * @tmpl: (type filename): template directory name
1387 * @mode: permissions to create the temporary directory with
1389 * Creates a temporary directory. See the mkdtemp() documentation
1390 * on most UNIX-like systems.
1392 * The parameter is a string that should follow the rules for
1393 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1394 * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1395 * sequence does not have to occur at the very end of the template
1396 * and you can pass a @mode. The X string will be modified to form
1397 * the name of a directory that didn't exist. The string should be
1398 * in the GLib file name encoding. Most importantly, on Windows it
1399 * should be in UTF-8.
1401 * Return value: A pointer to @tmpl, which has been modified
1402 * to hold the directory name. In case of errors, %NULL is
1403 * returned, and %errno will be set.
1408 g_mkdtemp_full (gchar *tmpl,
1411 if (get_tmp_file (tmpl, wrap_g_mkdir, 0, mode) == -1)
1419 * @tmpl: (type filename): template directory name
1421 * Creates a temporary directory. See the mkdtemp() documentation
1422 * on most UNIX-like systems.
1424 * The parameter is a string that should follow the rules for
1425 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1426 * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1427 * sequence does not have to occur at the very end of the template
1428 * and you can pass a @mode and additional @flags. The X string will
1429 * be modified to form the name of a directory that didn't exist.
1430 * The string should be in the GLib file name encoding. Most importantly,
1431 * on Windows it should be in UTF-8.
1433 * Return value: A pointer to @tmpl, which has been modified
1434 * to hold the directory name. In case of errors, %NULL is
1435 * returned and %errno will be set.
1440 g_mkdtemp (gchar *tmpl)
1442 return g_mkdtemp_full (tmpl, 0700);
1447 * @tmpl: (type filename): template filename
1448 * @flags: flags to pass to an open() call in addition to O_EXCL
1449 * and O_CREAT, which are passed automatically
1450 * @mode: permissions to create the temporary file with
1452 * Opens a temporary file. See the mkstemp() documentation
1453 * on most UNIX-like systems.
1455 * The parameter is a string that should follow the rules for
1456 * mkstemp() templates, i.e. contain the string "XXXXXX".
1457 * g_mkstemp_full() is slightly more flexible than mkstemp()
1458 * in that the sequence does not have to occur at the very end of the
1459 * template and you can pass a @mode and additional @flags. The X
1460 * string will be modified to form the name of a file that didn't exist.
1461 * The string should be in the GLib file name encoding. Most importantly,
1462 * on Windows it should be in UTF-8.
1464 * Return value: A file handle (as from open()) to the file
1465 * opened for reading and writing. The file handle should be
1466 * closed with close(). In case of errors, -1 is returned
1467 * and %errno will be set.
1472 g_mkstemp_full (gchar *tmpl,
1476 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1477 return get_tmp_file (tmpl, wrap_g_open,
1478 flags | O_CREAT | O_EXCL, mode);
1483 * @tmpl: (type filename): template filename
1485 * Opens a temporary file. See the mkstemp() documentation
1486 * on most UNIX-like systems.
1488 * The parameter is a string that should follow the rules for
1489 * mkstemp() templates, i.e. contain the string "XXXXXX".
1490 * g_mkstemp() is slightly more flexible than mkstemp() in that the
1491 * sequence does not have to occur at the very end of the template.
1492 * The X string will be modified to form the name of a file that
1493 * didn't exist. The string should be in the GLib file name encoding.
1494 * Most importantly, on Windows it should be in UTF-8.
1496 * Return value: A file handle (as from open()) to the file
1497 * opened for reading and writing. The file is opened in binary
1498 * mode on platforms where there is a difference. The file handle
1499 * should be closed with close(). In case of errors, -1 is
1500 * returned and %errno will be set.
1503 g_mkstemp (gchar *tmpl)
1505 return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1509 g_get_tmp_name (const gchar *tmpl,
1525 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1527 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1531 gchar *display_tmpl = g_filename_display_name (tmpl);
1538 G_FILE_ERROR_FAILED,
1539 _("Template '%s' invalid, should not contain a '%s'"),
1541 g_free (display_tmpl);
1546 if (strstr (tmpl, "XXXXXX") == NULL)
1548 gchar *display_tmpl = g_filename_display_name (tmpl);
1551 G_FILE_ERROR_FAILED,
1552 _("Template '%s' doesn't contain XXXXXX"),
1554 g_free (display_tmpl);
1558 tmpdir = g_get_tmp_dir ();
1560 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1563 sep = G_DIR_SEPARATOR_S;
1565 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1567 retval = get_tmp_file (fulltemplate, f, flags, mode);
1570 int save_errno = errno;
1571 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1575 g_file_error_from_errno (save_errno),
1576 _("Failed to create file '%s': %s"),
1577 display_fulltemplate, g_strerror (save_errno));
1578 g_free (display_fulltemplate);
1579 g_free (fulltemplate);
1583 *name_used = fulltemplate;
1590 * @tmpl: (type filename) (allow-none): Template for file name, as in
1591 * g_mkstemp(), basename only, or %NULL for a default template
1592 * @name_used: (out) (type filename): location to store actual name used,
1594 * @error: return location for a #GError
1596 * Opens a file for writing in the preferred directory for temporary
1597 * files (as returned by g_get_tmp_dir()).
1599 * @tmpl should be a string in the GLib file name encoding containing
1600 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1601 * However, unlike these functions, the template should only be a
1602 * basename, no directory components are allowed. If template is
1603 * %NULL, a default template is used.
1605 * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
1606 * modified, and might thus be a read-only literal string.
1608 * Upon success, and if @name_used is non-%NULL, the actual name used
1609 * is returned in @name_used. This string should be freed with g_free()
1610 * when not needed any longer. The returned name is in the GLib file
1613 * Return value: A file handle (as from open()) to the file opened for
1614 * reading and writing. The file is opened in binary mode on platforms
1615 * where there is a difference. The file handle should be closed with
1616 * close(). In case of errors, -1 is returned and @error will be set.
1619 g_file_open_tmp (const gchar *tmpl,
1623 gchar *fulltemplate;
1626 result = g_get_tmp_name (tmpl, &fulltemplate,
1628 O_CREAT | O_EXCL | O_RDWR | O_BINARY,
1634 *name_used = fulltemplate;
1636 g_free (fulltemplate);
1644 * @tmpl: (type filename) (allow-none): Template for directory name,
1645 * as in g_mkdtemp(), basename only, or %NULL for a default template
1646 * @error: return location for a #GError
1648 * Creates a subdirectory in the preferred directory for temporary
1649 * files (as returned by g_get_tmp_dir()).
1651 * @tmpl should be a string in the GLib file name encoding containing
1652 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1653 * However, unlike these functions, the template should only be a
1654 * basename, no directory components are allowed. If template is
1655 * %NULL, a default template is used.
1657 * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
1658 * modified, and might thus be a read-only literal string.
1660 * Return value: (type filename): The actual name used. This string
1661 * should be freed with g_free() when not needed any longer and is
1662 * is in the GLib file name encoding. In case of errors, %NULL is
1663 * returned and @error will be set.
1668 g_dir_make_tmp (const gchar *tmpl,
1671 gchar *fulltemplate;
1673 if (g_get_tmp_name (tmpl, &fulltemplate, wrap_g_mkdir, 0, 0700, error) == -1)
1676 return fulltemplate;
1680 g_build_path_va (const gchar *separator,
1681 const gchar *first_element,
1686 gint separator_len = strlen (separator);
1687 gboolean is_first = TRUE;
1688 gboolean have_leading = FALSE;
1689 const gchar *single_element = NULL;
1690 const gchar *next_element;
1691 const gchar *last_trailing = NULL;
1694 result = g_string_new (NULL);
1697 next_element = str_array[i++];
1699 next_element = first_element;
1703 const gchar *element;
1709 element = next_element;
1711 next_element = str_array[i++];
1713 next_element = va_arg (*args, gchar *);
1718 /* Ignore empty elements */
1726 while (strncmp (start, separator, separator_len) == 0)
1727 start += separator_len;
1730 end = start + strlen (start);
1734 while (end >= start + separator_len &&
1735 strncmp (end - separator_len, separator, separator_len) == 0)
1736 end -= separator_len;
1738 last_trailing = end;
1739 while (last_trailing >= element + separator_len &&
1740 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1741 last_trailing -= separator_len;
1745 /* If the leading and trailing separator strings are in the
1746 * same element and overlap, the result is exactly that element
1748 if (last_trailing <= start)
1749 single_element = element;
1751 g_string_append_len (result, element, start - element);
1752 have_leading = TRUE;
1755 single_element = NULL;
1762 g_string_append (result, separator);
1764 g_string_append_len (result, start, end - start);
1770 g_string_free (result, TRUE);
1771 return g_strdup (single_element);
1776 g_string_append (result, last_trailing);
1778 return g_string_free (result, FALSE);
1784 * @separator: a string used to separator the elements of the path.
1785 * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
1787 * Behaves exactly like g_build_path(), but takes the path elements
1788 * as a string array, instead of varargs. This function is mainly
1789 * meant for language bindings.
1791 * Return value: a newly-allocated string that must be freed with g_free().
1796 g_build_pathv (const gchar *separator,
1802 return g_build_path_va (separator, NULL, NULL, args);
1808 * @separator: a string used to separator the elements of the path.
1809 * @first_element: the first element in the path
1810 * @...: remaining elements in path, terminated by %NULL
1812 * Creates a path from a series of elements using @separator as the
1813 * separator between elements. At the boundary between two elements,
1814 * any trailing occurrences of separator in the first element, or
1815 * leading occurrences of separator in the second element are removed
1816 * and exactly one copy of the separator is inserted.
1818 * Empty elements are ignored.
1820 * The number of leading copies of the separator on the result is
1821 * the same as the number of leading copies of the separator on
1822 * the first non-empty element.
1824 * The number of trailing copies of the separator on the result is
1825 * the same as the number of trailing copies of the separator on
1826 * the last non-empty element. (Determination of the number of
1827 * trailing copies is done without stripping leading copies, so
1828 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1829 * has 1 trailing copy.)
1831 * However, if there is only a single non-empty element, and there
1832 * are no characters in that element not part of the leading or
1833 * trailing separators, then the result is exactly the original value
1836 * Other than for determination of the number of leading and trailing
1837 * copies of the separator, elements consisting only of copies
1838 * of the separator are ignored.
1840 * Return value: a newly-allocated string that must be freed with g_free().
1843 g_build_path (const gchar *separator,
1844 const gchar *first_element,
1850 g_return_val_if_fail (separator != NULL, NULL);
1852 va_start (args, first_element);
1853 str = g_build_path_va (separator, first_element, &args, NULL);
1862 g_build_pathname_va (const gchar *first_element,
1866 /* Code copied from g_build_pathv(), and modified to use two
1867 * alternative single-character separators.
1870 gboolean is_first = TRUE;
1871 gboolean have_leading = FALSE;
1872 const gchar *single_element = NULL;
1873 const gchar *next_element;
1874 const gchar *last_trailing = NULL;
1875 gchar current_separator = '\\';
1878 result = g_string_new (NULL);
1881 next_element = str_array[i++];
1883 next_element = first_element;
1887 const gchar *element;
1893 element = next_element;
1895 next_element = str_array[i++];
1897 next_element = va_arg (*args, gchar *);
1902 /* Ignore empty elements */
1911 (*start == '\\' || *start == '/'))
1913 current_separator = *start;
1918 end = start + strlen (start);
1922 while (end >= start + 1 &&
1923 (end[-1] == '\\' || end[-1] == '/'))
1925 current_separator = end[-1];
1929 last_trailing = end;
1930 while (last_trailing >= element + 1 &&
1931 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1936 /* If the leading and trailing separator strings are in the
1937 * same element and overlap, the result is exactly that element
1939 if (last_trailing <= start)
1940 single_element = element;
1942 g_string_append_len (result, element, start - element);
1943 have_leading = TRUE;
1946 single_element = NULL;
1953 g_string_append_len (result, ¤t_separator, 1);
1955 g_string_append_len (result, start, end - start);
1961 g_string_free (result, TRUE);
1962 return g_strdup (single_element);
1967 g_string_append (result, last_trailing);
1969 return g_string_free (result, FALSE);
1976 * g_build_filenamev:
1977 * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
1979 * Behaves exactly like g_build_filename(), but takes the path elements
1980 * as a string array, instead of varargs. This function is mainly
1981 * meant for language bindings.
1983 * Return value: a newly-allocated string that must be freed with g_free().
1988 g_build_filenamev (gchar **args)
1993 str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1995 str = g_build_pathname_va (NULL, NULL, args);
2003 * @first_element: the first element in the path
2004 * @...: remaining elements in path, terminated by %NULL
2006 * Creates a filename from a series of elements using the correct
2007 * separator for filenames.
2009 * On Unix, this function behaves identically to <literal>g_build_path
2010 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
2012 * On Windows, it takes into account that either the backslash
2013 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
2014 * as separator in filenames, but otherwise behaves as on Unix. When
2015 * file pathname separators need to be inserted, the one that last
2016 * previously occurred in the parameters (reading from left to right)
2019 * No attempt is made to force the resulting filename to be an absolute
2020 * path. If the first element is a relative path, the result will
2021 * be a relative path.
2023 * Return value: a newly-allocated string that must be freed with g_free().
2026 g_build_filename (const gchar *first_element,
2032 va_start (args, first_element);
2034 str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
2036 str = g_build_pathname_va (first_element, &args, NULL);
2045 * @filename: the symbolic link
2046 * @error: return location for a #GError
2048 * Reads the contents of the symbolic link @filename like the POSIX
2049 * readlink() function. The returned string is in the encoding used
2050 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
2052 * Returns: A newly-allocated string with the contents of the symbolic link,
2053 * or %NULL if an error occurred.
2058 g_file_read_link (const gchar *filename,
2061 #ifdef HAVE_READLINK
2067 buffer = g_malloc (size);
2071 read_size = readlink (filename, buffer, size);
2072 if (read_size < 0) {
2073 int save_errno = errno;
2074 gchar *display_filename = g_filename_display_name (filename);
2079 g_file_error_from_errno (save_errno),
2080 _("Failed to read the symbolic link '%s': %s"),
2082 g_strerror (save_errno));
2083 g_free (display_filename);
2088 if (read_size < size)
2090 buffer[read_size] = 0;
2095 buffer = g_realloc (buffer, size);
2098 g_set_error_literal (error,
2101 _("Symbolic links not supported"));
2108 * g_path_is_absolute:
2109 * @file_name: a file name
2111 * Returns %TRUE if the given @file_name is an absolute file name.
2112 * Note that this is a somewhat vague concept on Windows.
2114 * On POSIX systems, an absolute file name is well-defined. It always
2115 * starts from the single root directory. For example "/usr/local".
2117 * On Windows, the concepts of current drive and drive-specific
2118 * current directory introduce vagueness. This function interprets as
2119 * an absolute file name one that either begins with a directory
2120 * separator such as "\Users\tml" or begins with the root on a drive,
2121 * for example "C:\Windows". The first case also includes UNC paths
2122 * such as "\\myserver\docs\foo". In all cases, either slashes or
2123 * backslashes are accepted.
2125 * Note that a file name relative to the current drive root does not
2126 * truly specify a file uniquely over time and across processes, as
2127 * the current drive is a per-process value and can be changed.
2129 * File names relative the current directory on some specific drive,
2130 * such as "D:foo/bar", are not interpreted as absolute by this
2131 * function, but they obviously are not relative to the normal current
2132 * directory as returned by getcwd() or g_get_current_dir()
2133 * either. Such paths should be avoided, or need to be handled using
2134 * Windows-specific code.
2136 * Returns: %TRUE if @file_name is absolute
2139 g_path_is_absolute (const gchar *file_name)
2141 g_return_val_if_fail (file_name != NULL, FALSE);
2143 if (G_IS_DIR_SEPARATOR (file_name[0]))
2147 /* Recognize drive letter on native Windows */
2148 if (g_ascii_isalpha (file_name[0]) &&
2149 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
2158 * @file_name: a file name
2160 * Returns a pointer into @file_name after the root component,
2161 * i.e. after the "/" in UNIX or "C:\" under Windows. If @file_name
2162 * is not an absolute path it returns %NULL.
2164 * Returns: a pointer into @file_name after the root component
2167 g_path_skip_root (const gchar *file_name)
2169 g_return_val_if_fail (file_name != NULL, NULL);
2171 #ifdef G_PLATFORM_WIN32
2172 /* Skip \\server\share or //server/share */
2173 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2174 G_IS_DIR_SEPARATOR (file_name[1]) &&
2176 !G_IS_DIR_SEPARATOR (file_name[2]))
2179 p = strchr (file_name + 2, G_DIR_SEPARATOR);
2185 q = strchr (file_name + 2, '/');
2186 if (p == NULL || (q != NULL && q < p))
2191 if (p && p > file_name + 2 && p[1])
2195 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
2198 /* Possibly skip a backslash after the share name */
2199 if (G_IS_DIR_SEPARATOR (file_name[0]))
2202 return (gchar *)file_name;
2207 /* Skip initial slashes */
2208 if (G_IS_DIR_SEPARATOR (file_name[0]))
2210 while (G_IS_DIR_SEPARATOR (file_name[0]))
2212 return (gchar *)file_name;
2217 if (g_ascii_isalpha (file_name[0]) &&
2218 file_name[1] == ':' &&
2219 G_IS_DIR_SEPARATOR (file_name[2]))
2220 return (gchar *)file_name + 3;
2228 * @file_name: the name of the file
2230 * Gets the name of the file without any leading directory
2231 * components. It returns a pointer into the given file name
2234 * Return value: the name of the file without any leading
2235 * directory components
2237 * Deprecated:2.2: Use g_path_get_basename() instead, but notice
2238 * that g_path_get_basename() allocates new memory for the
2239 * returned string, unlike this function which returns a pointer
2240 * into the argument.
2243 g_basename (const gchar *file_name)
2247 g_return_val_if_fail (file_name != NULL, NULL);
2249 base = strrchr (file_name, G_DIR_SEPARATOR);
2254 q = strrchr (file_name, '/');
2255 if (base == NULL || (q != NULL && q > base))
2264 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2265 return (gchar*) file_name + 2;
2268 return (gchar*) file_name;
2272 * g_path_get_basename:
2273 * @file_name: the name of the file
2275 * Gets the last component of the filename.
2277 * If @file_name ends with a directory separator it gets the component
2278 * before the last slash. If @file_name consists only of directory
2279 * separators (and on Windows, possibly a drive letter), a single
2280 * separator is returned. If @file_name is empty, it gets ".".
2282 * Return value: a newly allocated string containing the last
2283 * component of the filename
2286 g_path_get_basename (const gchar *file_name)
2289 gssize last_nonslash;
2293 g_return_val_if_fail (file_name != NULL, NULL);
2295 if (file_name[0] == '\0')
2296 return g_strdup (".");
2298 last_nonslash = strlen (file_name) - 1;
2300 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
2303 if (last_nonslash == -1)
2304 /* string only containing slashes */
2305 return g_strdup (G_DIR_SEPARATOR_S);
2308 if (last_nonslash == 1 &&
2309 g_ascii_isalpha (file_name[0]) &&
2310 file_name[1] == ':')
2311 /* string only containing slashes and a drive */
2312 return g_strdup (G_DIR_SEPARATOR_S);
2314 base = last_nonslash;
2316 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
2321 g_ascii_isalpha (file_name[0]) &&
2322 file_name[1] == ':')
2324 #endif /* G_OS_WIN32 */
2326 len = last_nonslash - base;
2327 retval = g_malloc (len + 1);
2328 memcpy (retval, file_name + base + 1, len);
2329 retval [len] = '\0';
2336 * @file_name: the name of the file
2338 * Gets the directory components of a file name.
2340 * If the file name has no directory components "." is returned.
2341 * The returned string should be freed when no longer needed.
2343 * Returns: the directory components of the file
2345 * Deprecated: use g_path_get_dirname() instead
2349 * g_path_get_dirname:
2350 * @file_name: the name of the file
2352 * Gets the directory components of a file name.
2354 * If the file name has no directory components "." is returned.
2355 * The returned string should be freed when no longer needed.
2357 * Returns: the directory components of the file
2360 g_path_get_dirname (const gchar *file_name)
2365 g_return_val_if_fail (file_name != NULL, NULL);
2367 base = strrchr (file_name, G_DIR_SEPARATOR);
2372 q = strrchr (file_name, '/');
2373 if (base == NULL || (q != NULL && q > base))
2381 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2383 gchar drive_colon_dot[4];
2385 drive_colon_dot[0] = file_name[0];
2386 drive_colon_dot[1] = ':';
2387 drive_colon_dot[2] = '.';
2388 drive_colon_dot[3] = '\0';
2390 return g_strdup (drive_colon_dot);
2393 return g_strdup (".");
2396 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
2400 /* base points to the char before the last slash.
2402 * In case file_name is the root of a drive (X:\) or a child of the
2403 * root of a drive (X:\foo), include the slash.
2405 * In case file_name is the root share of an UNC path
2406 * (\\server\share), add a slash, returning \\server\share\ .
2408 * In case file_name is a direct child of a share in an UNC path
2409 * (\\server\share\foo), include the slash after the share name,
2410 * returning \\server\share\ .
2412 if (base == file_name + 1 &&
2413 g_ascii_isalpha (file_name[0]) &&
2414 file_name[1] == ':')
2416 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2417 G_IS_DIR_SEPARATOR (file_name[1]) &&
2419 !G_IS_DIR_SEPARATOR (file_name[2]) &&
2420 base >= file_name + 2)
2422 const gchar *p = file_name + 2;
2423 while (*p && !G_IS_DIR_SEPARATOR (*p))
2427 len = (guint) strlen (file_name) + 1;
2428 base = g_new (gchar, len + 1);
2429 strcpy (base, file_name);
2430 base[len-1] = G_DIR_SEPARATOR;
2434 if (G_IS_DIR_SEPARATOR (*p))
2437 while (*p && !G_IS_DIR_SEPARATOR (*p))
2445 len = (guint) 1 + base - file_name;
2446 base = g_new (gchar, len + 1);
2447 g_memmove (base, file_name, len);
2453 #if defined(MAXPATHLEN)
2454 #define G_PATH_LENGTH MAXPATHLEN
2455 #elif defined(PATH_MAX)
2456 #define G_PATH_LENGTH PATH_MAX
2457 #elif defined(_PC_PATH_MAX)
2458 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
2460 #define G_PATH_LENGTH 2048
2464 * g_get_current_dir:
2466 * Gets the current directory.
2468 * The returned string should be freed when no longer needed.
2469 * The encoding of the returned string is system defined.
2470 * On Windows, it is always UTF-8.
2472 * Returns: the current directory
2475 g_get_current_dir (void)
2480 wchar_t dummy[2], *wdir;
2483 len = GetCurrentDirectoryW (2, dummy);
2484 wdir = g_new (wchar_t, len);
2486 if (GetCurrentDirectoryW (len, wdir) == len - 1)
2487 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
2492 dir = g_strdup ("\\");
2498 gchar *buffer = NULL;
2500 static gulong max_len = 0;
2503 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
2505 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
2506 * and, if that wasn't bad enough, hangs in doing so.
2508 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
2509 buffer = g_new (gchar, max_len + 1);
2511 dir = getwd (buffer);
2513 while (max_len < G_MAXULONG / 2)
2516 buffer = g_new (gchar, max_len + 1);
2518 dir = getcwd (buffer, max_len);
2520 if (dir || errno != ERANGE)
2525 #endif /* !sun || !HAVE_GETCWD */
2527 if (!dir || !*buffer)
2529 /* hm, should we g_error() out here?
2530 * this can happen if e.g. "./" has mode \0000
2532 buffer[0] = G_DIR_SEPARATOR;
2536 dir = g_strdup (buffer);
2541 #endif /* !G_OS_WIN32 */
2545 /* NOTE : Keep this part last to ensure nothing in this file uses thn
2546 * below binary compatibility versions.
2548 #if defined (G_OS_WIN32) && !defined (_WIN64)
2550 /* Binary compatibility versions. Will be called by code compiled
2551 * against quite old (pre-2.8, I think) headers only, not from more
2552 * recently compiled code.
2558 g_file_test (const gchar *filename,
2561 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
2564 if (utf8_filename == NULL)
2567 retval = g_file_test_utf8 (utf8_filename, test);
2569 g_free (utf8_filename);
2574 #undef g_file_get_contents
2577 g_file_get_contents (const gchar *filename,
2582 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
2585 if (utf8_filename == NULL)
2588 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
2590 g_free (utf8_filename);
2598 wrap_libc_open (const gchar *filename,
2602 return open (filename, flags, mode);
2606 g_mkstemp (gchar *tmpl)
2608 /* This is the backward compatibility system codepage version,
2609 * thus use normal open().
2611 return get_tmp_file (tmpl, wrap_libc_open,
2612 O_RDWR | O_CREAT | O_EXCL, 0600);
2615 #undef g_file_open_tmp
2618 g_file_open_tmp (const gchar *tmpl,
2622 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
2623 gchar *utf8_name_used;
2626 if (utf8_tmpl == NULL)
2629 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
2635 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
2637 g_free (utf8_name_used);
2642 #undef g_get_current_dir
2645 g_get_current_dir (void)
2647 gchar *utf8_dir = g_get_current_dir_utf8 ();
2648 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);