Merge branch 'macosx-ci' into 'master'
[glib.git] / glib / gfileutils.c
blob380c8d147d31a1f1a07f62d09c39fc1647c52a4e
1 /* gfileutils.c - File utility functions
3 * Copyright 2000 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public License
16 * along with this library; if not, see <http://www.gnu.org/licenses/>.
19 #include "config.h"
20 #include "glibconfig.h"
22 #include <sys/stat.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <fcntl.h>
31 #include <stdlib.h>
33 #ifdef G_OS_UNIX
34 #include <unistd.h>
35 #endif
36 #ifdef G_OS_WIN32
37 #include <windows.h>
38 #include <io.h>
39 #endif /* G_OS_WIN32 */
41 #ifndef S_ISLNK
42 #define S_ISLNK(x) 0
43 #endif
45 #ifndef O_BINARY
46 #define O_BINARY 0
47 #endif
49 #include "gfileutils.h"
51 #include "gstdio.h"
52 #include "gstdioprivate.h"
53 #include "glibintl.h"
55 #ifdef HAVE_LINUX_MAGIC_H /* for btrfs check */
56 #include <linux/magic.h>
57 #include <sys/vfs.h>
58 #endif
61 /**
62 * SECTION:fileutils
63 * @title: File Utilities
64 * @short_description: various file-related functions
66 * Do not use these APIs unless you are porting a POSIX application to Windows.
67 * A more high-level file access API is provided as GIO — see the documentation
68 * for #GFile.
70 * There is a group of functions which wrap the common POSIX functions
71 * dealing with filenames (g_open(), g_rename(), g_mkdir(), g_stat(),
72 * g_unlink(), g_remove(), g_fopen(), g_freopen()). The point of these
73 * wrappers is to make it possible to handle file names with any Unicode
74 * characters in them on Windows without having to use ifdefs and the
75 * wide character API in the application code.
77 * On some Unix systems, these APIs may be defined as identical to their POSIX
78 * counterparts. For this reason, you must check for and include the necessary
79 * header files (such as `fcntl.h`) before using functions like g_creat(). You
80 * must also define the relevant feature test macros.
82 * The pathname argument should be in the GLib file name encoding.
83 * On POSIX this is the actual on-disk encoding which might correspond
84 * to the locale settings of the process (or the `G_FILENAME_ENCODING`
85 * environment variable), or not.
87 * On Windows the GLib file name encoding is UTF-8. Note that the
88 * Microsoft C library does not use UTF-8, but has separate APIs for
89 * current system code page and wide characters (UTF-16). The GLib
90 * wrappers call the wide character API if present (on modern Windows
91 * systems), otherwise convert to/from the system code page.
93 * Another group of functions allows to open and read directories
94 * in the GLib file name encoding. These are g_dir_open(),
95 * g_dir_read_name(), g_dir_rewind(), g_dir_close().
98 /**
99 * GFileError:
100 * @G_FILE_ERROR_EXIST: Operation not permitted; only the owner of
101 * the file (or other resource) or processes with special privileges
102 * can perform the operation.
103 * @G_FILE_ERROR_ISDIR: File is a directory; you cannot open a directory
104 * for writing, or create or remove hard links to it.
105 * @G_FILE_ERROR_ACCES: Permission denied; the file permissions do not
106 * allow the attempted operation.
107 * @G_FILE_ERROR_NAMETOOLONG: Filename too long.
108 * @G_FILE_ERROR_NOENT: No such file or directory. This is a "file
109 * doesn't exist" error for ordinary files that are referenced in
110 * contexts where they are expected to already exist.
111 * @G_FILE_ERROR_NOTDIR: A file that isn't a directory was specified when
112 * a directory is required.
113 * @G_FILE_ERROR_NXIO: No such device or address. The system tried to
114 * use the device represented by a file you specified, and it
115 * couldn't find the device. This can mean that the device file was
116 * installed incorrectly, or that the physical device is missing or
117 * not correctly attached to the computer.
118 * @G_FILE_ERROR_NODEV: The underlying file system of the specified file
119 * does not support memory mapping.
120 * @G_FILE_ERROR_ROFS: The directory containing the new link can't be
121 * modified because it's on a read-only file system.
122 * @G_FILE_ERROR_TXTBSY: Text file busy.
123 * @G_FILE_ERROR_FAULT: You passed in a pointer to bad memory.
124 * (GLib won't reliably return this, don't pass in pointers to bad
125 * memory.)
126 * @G_FILE_ERROR_LOOP: Too many levels of symbolic links were encountered
127 * in looking up a file name. This often indicates a cycle of symbolic
128 * links.
129 * @G_FILE_ERROR_NOSPC: No space left on device; write operation on a
130 * file failed because the disk is full.
131 * @G_FILE_ERROR_NOMEM: No memory available. The system cannot allocate
132 * more virtual memory because its capacity is full.
133 * @G_FILE_ERROR_MFILE: The current process has too many files open and
134 * can't open any more. Duplicate descriptors do count toward this
135 * limit.
136 * @G_FILE_ERROR_NFILE: There are too many distinct file openings in the
137 * entire system.
138 * @G_FILE_ERROR_BADF: Bad file descriptor; for example, I/O on a
139 * descriptor that has been closed or reading from a descriptor open
140 * only for writing (or vice versa).
141 * @G_FILE_ERROR_INVAL: Invalid argument. This is used to indicate
142 * various kinds of problems with passing the wrong argument to a
143 * library function.
144 * @G_FILE_ERROR_PIPE: Broken pipe; there is no process reading from the
145 * other end of a pipe. Every library function that returns this
146 * error code also generates a 'SIGPIPE' signal; this signal
147 * terminates the program if not handled or blocked. Thus, your
148 * program will never actually see this code unless it has handled
149 * or blocked 'SIGPIPE'.
150 * @G_FILE_ERROR_AGAIN: Resource temporarily unavailable; the call might
151 * work if you try again later.
152 * @G_FILE_ERROR_INTR: Interrupted function call; an asynchronous signal
153 * occurred and prevented completion of the call. When this
154 * happens, you should try the call again.
155 * @G_FILE_ERROR_IO: Input/output error; usually used for physical read
156 * or write errors. i.e. the disk or other physical device hardware
157 * is returning errors.
158 * @G_FILE_ERROR_PERM: Operation not permitted; only the owner of the
159 * file (or other resource) or processes with special privileges can
160 * perform the operation.
161 * @G_FILE_ERROR_NOSYS: Function not implemented; this indicates that
162 * the system is missing some functionality.
163 * @G_FILE_ERROR_FAILED: Does not correspond to a UNIX error code; this
164 * is the standard "failed for unspecified reason" error code present
165 * in all #GError error code enumerations. Returned if no specific
166 * code applies.
168 * Values corresponding to @errno codes returned from file operations
169 * on UNIX. Unlike @errno codes, GFileError values are available on
170 * all systems, even Windows. The exact meaning of each code depends
171 * on what sort of file operation you were performing; the UNIX
172 * documentation gives more details. The following error code descriptions
173 * come from the GNU C Library manual, and are under the copyright
174 * of that manual.
176 * It's not very portable to make detailed assumptions about exactly
177 * which errors will be returned from a given operation. Some errors
178 * don't occur on some systems, etc., sometimes there are subtle
179 * differences in when a system will report a given error, etc.
183 * G_FILE_ERROR:
185 * Error domain for file operations. Errors in this domain will
186 * be from the #GFileError enumeration. See #GError for information
187 * on error domains.
191 * GFileTest:
192 * @G_FILE_TEST_IS_REGULAR: %TRUE if the file is a regular file
193 * (not a directory). Note that this test will also return %TRUE
194 * if the tested file is a symlink to a regular file.
195 * @G_FILE_TEST_IS_SYMLINK: %TRUE if the file is a symlink.
196 * @G_FILE_TEST_IS_DIR: %TRUE if the file is a directory.
197 * @G_FILE_TEST_IS_EXECUTABLE: %TRUE if the file is executable.
198 * @G_FILE_TEST_EXISTS: %TRUE if the file exists. It may or may not
199 * be a regular file.
201 * A test to perform on a file using g_file_test().
205 * g_mkdir_with_parents:
206 * @pathname: (type filename): a pathname in the GLib file name encoding
207 * @mode: permissions to use for newly created directories
209 * Create a directory if it doesn't already exist. Create intermediate
210 * parent directories as needed, too.
212 * Returns: 0 if the directory already exists, or was successfully
213 * created. Returns -1 if an error occurred, with errno set.
215 * Since: 2.8
218 g_mkdir_with_parents (const gchar *pathname,
219 int mode)
221 gchar *fn, *p;
223 if (pathname == NULL || *pathname == '\0')
225 errno = EINVAL;
226 return -1;
229 fn = g_strdup (pathname);
231 if (g_path_is_absolute (fn))
232 p = (gchar *) g_path_skip_root (fn);
233 else
234 p = fn;
238 while (*p && !G_IS_DIR_SEPARATOR (*p))
239 p++;
241 if (!*p)
242 p = NULL;
243 else
244 *p = '\0';
246 if (!g_file_test (fn, G_FILE_TEST_EXISTS))
248 if (g_mkdir (fn, mode) == -1 && errno != EEXIST)
250 int errno_save = errno;
251 g_free (fn);
252 errno = errno_save;
253 return -1;
256 else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
258 g_free (fn);
259 errno = ENOTDIR;
260 return -1;
262 if (p)
264 *p++ = G_DIR_SEPARATOR;
265 while (*p && G_IS_DIR_SEPARATOR (*p))
266 p++;
269 while (p);
271 g_free (fn);
273 return 0;
277 * g_file_test:
278 * @filename: (type filename): a filename to test in the
279 * GLib file name encoding
280 * @test: bitfield of #GFileTest flags
282 * Returns %TRUE if any of the tests in the bitfield @test are
283 * %TRUE. For example, `(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)`
284 * will return %TRUE if the file exists; the check whether it's a
285 * directory doesn't matter since the existence test is %TRUE. With
286 * the current set of available tests, there's no point passing in
287 * more than one test at a time.
289 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
290 * so for a symbolic link to a regular file g_file_test() will return
291 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
293 * Note, that for a dangling symbolic link g_file_test() will return
294 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
296 * You should never use g_file_test() to test whether it is safe
297 * to perform an operation, because there is always the possibility
298 * of the condition changing before you actually perform the operation.
299 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
300 * to know whether it is safe to write to a file without being
301 * tricked into writing into a different location. It doesn't work!
302 * |[<!-- language="C" -->
303 * // DON'T DO THIS
304 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
306 * fd = g_open (filename, O_WRONLY);
307 * // write to fd
309 * ]|
311 * Another thing to note is that %G_FILE_TEST_EXISTS and
312 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
313 * system call. This usually doesn't matter, but if your program
314 * is setuid or setgid it means that these tests will give you
315 * the answer for the real user ID and group ID, rather than the
316 * effective user ID and group ID.
318 * On Windows, there are no symlinks, so testing for
319 * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
320 * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
321 * its name indicates that it is executable, checking for well-known
322 * extensions and those listed in the `PATHEXT` environment variable.
324 * Returns: whether a test was %TRUE
326 gboolean
327 g_file_test (const gchar *filename,
328 GFileTest test)
330 #ifdef G_OS_WIN32
331 int attributes;
332 wchar_t *wfilename;
333 #endif
335 g_return_val_if_fail (filename != NULL, FALSE);
337 #ifdef G_OS_WIN32
338 /* stuff missing in std vc6 api */
339 # ifndef INVALID_FILE_ATTRIBUTES
340 # define INVALID_FILE_ATTRIBUTES -1
341 # endif
342 # ifndef FILE_ATTRIBUTE_DEVICE
343 # define FILE_ATTRIBUTE_DEVICE 64
344 # endif
345 wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
347 if (wfilename == NULL)
348 return FALSE;
350 attributes = GetFileAttributesW (wfilename);
352 g_free (wfilename);
354 if (attributes == INVALID_FILE_ATTRIBUTES)
355 return FALSE;
357 if (test & G_FILE_TEST_EXISTS)
358 return TRUE;
360 if (test & G_FILE_TEST_IS_REGULAR)
362 if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0)
363 return TRUE;
366 if (test & G_FILE_TEST_IS_DIR)
368 if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
369 return TRUE;
372 /* "while" so that we can exit this "loop" with a simple "break" */
373 while (test & G_FILE_TEST_IS_EXECUTABLE)
375 const gchar *lastdot = strrchr (filename, '.');
376 const gchar *pathext = NULL, *p;
377 int extlen;
379 if (lastdot == NULL)
380 break;
382 if (_stricmp (lastdot, ".exe") == 0 ||
383 _stricmp (lastdot, ".cmd") == 0 ||
384 _stricmp (lastdot, ".bat") == 0 ||
385 _stricmp (lastdot, ".com") == 0)
386 return TRUE;
388 /* Check if it is one of the types listed in %PATHEXT% */
390 pathext = g_getenv ("PATHEXT");
391 if (pathext == NULL)
392 break;
394 pathext = g_utf8_casefold (pathext, -1);
396 lastdot = g_utf8_casefold (lastdot, -1);
397 extlen = strlen (lastdot);
399 p = pathext;
400 while (TRUE)
402 const gchar *q = strchr (p, ';');
403 if (q == NULL)
404 q = p + strlen (p);
405 if (extlen == q - p &&
406 memcmp (lastdot, p, extlen) == 0)
408 g_free ((gchar *) pathext);
409 g_free ((gchar *) lastdot);
410 return TRUE;
412 if (*q)
413 p = q + 1;
414 else
415 break;
418 g_free ((gchar *) pathext);
419 g_free ((gchar *) lastdot);
420 break;
423 return FALSE;
424 #else
425 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
426 return TRUE;
428 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
430 if (getuid () != 0)
431 return TRUE;
433 /* For root, on some POSIX systems, access (filename, X_OK)
434 * will succeed even if no executable bits are set on the
435 * file. We fall through to a stat test to avoid that.
438 else
439 test &= ~G_FILE_TEST_IS_EXECUTABLE;
441 if (test & G_FILE_TEST_IS_SYMLINK)
443 struct stat s;
445 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
446 return TRUE;
449 if (test & (G_FILE_TEST_IS_REGULAR |
450 G_FILE_TEST_IS_DIR |
451 G_FILE_TEST_IS_EXECUTABLE))
453 struct stat s;
455 if (stat (filename, &s) == 0)
457 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
458 return TRUE;
460 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
461 return TRUE;
463 /* The extra test for root when access (file, X_OK) succeeds.
465 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
466 ((s.st_mode & S_IXOTH) ||
467 (s.st_mode & S_IXUSR) ||
468 (s.st_mode & S_IXGRP)))
469 return TRUE;
473 return FALSE;
474 #endif
477 G_DEFINE_QUARK (g-file-error-quark, g_file_error)
480 * g_file_error_from_errno:
481 * @err_no: an "errno" value
483 * Gets a #GFileError constant based on the passed-in @err_no.
484 * For example, if you pass in `EEXIST` this function returns
485 * #G_FILE_ERROR_EXIST. Unlike `errno` values, you can portably
486 * assume that all #GFileError values will exist.
488 * Normally a #GFileError value goes into a #GError returned
489 * from a function that manipulates files. So you would use
490 * g_file_error_from_errno() when constructing a #GError.
492 * Returns: #GFileError corresponding to the given @errno
494 GFileError
495 g_file_error_from_errno (gint err_no)
497 switch (err_no)
499 #ifdef EEXIST
500 case EEXIST:
501 return G_FILE_ERROR_EXIST;
502 #endif
504 #ifdef EISDIR
505 case EISDIR:
506 return G_FILE_ERROR_ISDIR;
507 #endif
509 #ifdef EACCES
510 case EACCES:
511 return G_FILE_ERROR_ACCES;
512 #endif
514 #ifdef ENAMETOOLONG
515 case ENAMETOOLONG:
516 return G_FILE_ERROR_NAMETOOLONG;
517 #endif
519 #ifdef ENOENT
520 case ENOENT:
521 return G_FILE_ERROR_NOENT;
522 #endif
524 #ifdef ENOTDIR
525 case ENOTDIR:
526 return G_FILE_ERROR_NOTDIR;
527 #endif
529 #ifdef ENXIO
530 case ENXIO:
531 return G_FILE_ERROR_NXIO;
532 #endif
534 #ifdef ENODEV
535 case ENODEV:
536 return G_FILE_ERROR_NODEV;
537 #endif
539 #ifdef EROFS
540 case EROFS:
541 return G_FILE_ERROR_ROFS;
542 #endif
544 #ifdef ETXTBSY
545 case ETXTBSY:
546 return G_FILE_ERROR_TXTBSY;
547 #endif
549 #ifdef EFAULT
550 case EFAULT:
551 return G_FILE_ERROR_FAULT;
552 #endif
554 #ifdef ELOOP
555 case ELOOP:
556 return G_FILE_ERROR_LOOP;
557 #endif
559 #ifdef ENOSPC
560 case ENOSPC:
561 return G_FILE_ERROR_NOSPC;
562 #endif
564 #ifdef ENOMEM
565 case ENOMEM:
566 return G_FILE_ERROR_NOMEM;
567 #endif
569 #ifdef EMFILE
570 case EMFILE:
571 return G_FILE_ERROR_MFILE;
572 #endif
574 #ifdef ENFILE
575 case ENFILE:
576 return G_FILE_ERROR_NFILE;
577 #endif
579 #ifdef EBADF
580 case EBADF:
581 return G_FILE_ERROR_BADF;
582 #endif
584 #ifdef EINVAL
585 case EINVAL:
586 return G_FILE_ERROR_INVAL;
587 #endif
589 #ifdef EPIPE
590 case EPIPE:
591 return G_FILE_ERROR_PIPE;
592 #endif
594 #ifdef EAGAIN
595 case EAGAIN:
596 return G_FILE_ERROR_AGAIN;
597 #endif
599 #ifdef EINTR
600 case EINTR:
601 return G_FILE_ERROR_INTR;
602 #endif
604 #ifdef EIO
605 case EIO:
606 return G_FILE_ERROR_IO;
607 #endif
609 #ifdef EPERM
610 case EPERM:
611 return G_FILE_ERROR_PERM;
612 #endif
614 #ifdef ENOSYS
615 case ENOSYS:
616 return G_FILE_ERROR_NOSYS;
617 #endif
619 default:
620 return G_FILE_ERROR_FAILED;
624 static char *
625 format_error_message (const gchar *filename,
626 const gchar *format_string,
627 int saved_errno) G_GNUC_FORMAT(2);
629 #pragma GCC diagnostic push
630 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
632 static char *
633 format_error_message (const gchar *filename,
634 const gchar *format_string,
635 int saved_errno)
637 gchar *display_name;
638 gchar *msg;
640 display_name = g_filename_display_name (filename);
641 msg = g_strdup_printf (format_string, display_name, g_strerror (saved_errno));
642 g_free (display_name);
644 return msg;
647 #pragma GCC diagnostic pop
649 /* format string must have two '%s':
651 * - the place for the filename
652 * - the place for the strerror
654 static void
655 set_file_error (GError **error,
656 const gchar *filename,
657 const gchar *format_string,
658 int saved_errno)
660 char *msg = format_error_message (filename, format_string, saved_errno);
662 g_set_error_literal (error, G_FILE_ERROR, g_file_error_from_errno (saved_errno),
663 msg);
664 g_free (msg);
667 static gboolean
668 get_contents_stdio (const gchar *filename,
669 FILE *f,
670 gchar **contents,
671 gsize *length,
672 GError **error)
674 gchar buf[4096];
675 gsize bytes; /* always <= sizeof(buf) */
676 gchar *str = NULL;
677 gsize total_bytes = 0;
678 gsize total_allocated = 0;
679 gchar *tmp;
680 gchar *display_filename;
682 g_assert (f != NULL);
684 while (!feof (f))
686 gint save_errno;
688 bytes = fread (buf, 1, sizeof (buf), f);
689 save_errno = errno;
691 if (total_bytes > G_MAXSIZE - bytes)
692 goto file_too_large;
694 /* Possibility of overflow eliminated above. */
695 while (total_bytes + bytes >= total_allocated)
697 if (str)
699 if (total_allocated > G_MAXSIZE / 2)
700 goto file_too_large;
701 total_allocated *= 2;
703 else
705 total_allocated = MIN (bytes + 1, sizeof (buf));
708 tmp = g_try_realloc (str, total_allocated);
710 if (tmp == NULL)
712 display_filename = g_filename_display_name (filename);
713 g_set_error (error,
714 G_FILE_ERROR,
715 G_FILE_ERROR_NOMEM,
716 g_dngettext (GETTEXT_PACKAGE, "Could not allocate %lu byte to read file “%s”", "Could not allocate %lu bytes to read file “%s”", (gulong)total_allocated),
717 (gulong) total_allocated,
718 display_filename);
719 g_free (display_filename);
721 goto error;
724 str = tmp;
727 if (ferror (f))
729 display_filename = g_filename_display_name (filename);
730 g_set_error (error,
731 G_FILE_ERROR,
732 g_file_error_from_errno (save_errno),
733 _("Error reading file “%s”: %s"),
734 display_filename,
735 g_strerror (save_errno));
736 g_free (display_filename);
738 goto error;
741 g_assert (str != NULL);
742 memcpy (str + total_bytes, buf, bytes);
744 total_bytes += bytes;
747 fclose (f);
749 if (total_allocated == 0)
751 str = g_new (gchar, 1);
752 total_bytes = 0;
755 str[total_bytes] = '\0';
757 if (length)
758 *length = total_bytes;
760 *contents = str;
762 return TRUE;
764 file_too_large:
765 display_filename = g_filename_display_name (filename);
766 g_set_error (error,
767 G_FILE_ERROR,
768 G_FILE_ERROR_FAILED,
769 _("File “%s” is too large"),
770 display_filename);
771 g_free (display_filename);
773 error:
775 g_free (str);
776 fclose (f);
778 return FALSE;
781 #ifndef G_OS_WIN32
783 static gboolean
784 get_contents_regfile (const gchar *filename,
785 struct stat *stat_buf,
786 gint fd,
787 gchar **contents,
788 gsize *length,
789 GError **error)
791 gchar *buf;
792 gsize bytes_read;
793 gsize size;
794 gsize alloc_size;
795 gchar *display_filename;
797 size = stat_buf->st_size;
799 alloc_size = size + 1;
800 buf = g_try_malloc (alloc_size);
802 if (buf == NULL)
804 display_filename = g_filename_display_name (filename);
805 g_set_error (error,
806 G_FILE_ERROR,
807 G_FILE_ERROR_NOMEM,
808 g_dngettext (GETTEXT_PACKAGE, "Could not allocate %lu byte to read file “%s”", "Could not allocate %lu bytes to read file “%s”", (gulong)alloc_size),
809 (gulong) alloc_size,
810 display_filename);
811 g_free (display_filename);
812 goto error;
815 bytes_read = 0;
816 while (bytes_read < size)
818 gssize rc;
820 rc = read (fd, buf + bytes_read, size - bytes_read);
822 if (rc < 0)
824 if (errno != EINTR)
826 int save_errno = errno;
828 g_free (buf);
829 display_filename = g_filename_display_name (filename);
830 g_set_error (error,
831 G_FILE_ERROR,
832 g_file_error_from_errno (save_errno),
833 _("Failed to read from file “%s”: %s"),
834 display_filename,
835 g_strerror (save_errno));
836 g_free (display_filename);
837 goto error;
840 else if (rc == 0)
841 break;
842 else
843 bytes_read += rc;
846 buf[bytes_read] = '\0';
848 if (length)
849 *length = bytes_read;
851 *contents = buf;
853 close (fd);
855 return TRUE;
857 error:
859 close (fd);
861 return FALSE;
864 static gboolean
865 get_contents_posix (const gchar *filename,
866 gchar **contents,
867 gsize *length,
868 GError **error)
870 struct stat stat_buf;
871 gint fd;
873 /* O_BINARY useful on Cygwin */
874 fd = open (filename, O_RDONLY|O_BINARY);
876 if (fd < 0)
878 int saved_errno = errno;
879 set_file_error (error,
880 filename,
881 _("Failed to open file “%s”: %s"),
882 saved_errno);
884 return FALSE;
887 /* I don't think this will ever fail, aside from ENOMEM, but. */
888 if (fstat (fd, &stat_buf) < 0)
890 int saved_errno = errno;
891 set_file_error (error,
892 filename,
893 _("Failed to get attributes of file “%s”: fstat() failed: %s"),
894 saved_errno);
895 close (fd);
897 return FALSE;
900 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
902 gboolean retval = get_contents_regfile (filename,
903 &stat_buf,
905 contents,
906 length,
907 error);
909 return retval;
911 else
913 FILE *f;
914 gboolean retval;
916 f = fdopen (fd, "r");
918 if (f == NULL)
920 int saved_errno = errno;
921 set_file_error (error,
922 filename,
923 _("Failed to open file “%s”: fdopen() failed: %s"),
924 saved_errno);
926 return FALSE;
929 retval = get_contents_stdio (filename, f, contents, length, error);
931 return retval;
935 #else /* G_OS_WIN32 */
937 static gboolean
938 get_contents_win32 (const gchar *filename,
939 gchar **contents,
940 gsize *length,
941 GError **error)
943 FILE *f;
944 gboolean retval;
946 f = g_fopen (filename, "rb");
948 if (f == NULL)
950 int saved_errno = errno;
951 set_file_error (error,
952 filename,
953 _("Failed to open file “%s”: %s"),
954 saved_errno);
956 return FALSE;
959 retval = get_contents_stdio (filename, f, contents, length, error);
961 return retval;
964 #endif
967 * g_file_get_contents:
968 * @filename: (type filename): name of a file to read contents from, in the GLib file name encoding
969 * @contents: (out) (array length=length) (element-type guint8): location to store an allocated string, use g_free() to free
970 * the returned string
971 * @length: (nullable): location to store length in bytes of the contents, or %NULL
972 * @error: return location for a #GError, or %NULL
974 * Reads an entire file into allocated memory, with good error
975 * checking.
977 * If the call was successful, it returns %TRUE and sets @contents to the file
978 * contents and @length to the length of the file contents in bytes. The string
979 * stored in @contents will be nul-terminated, so for text files you can pass
980 * %NULL for the @length argument. If the call was not successful, it returns
981 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
982 * codes are those in the #GFileError enumeration. In the error case,
983 * @contents is set to %NULL and @length is set to zero.
985 * Returns: %TRUE on success, %FALSE if an error occurred
987 gboolean
988 g_file_get_contents (const gchar *filename,
989 gchar **contents,
990 gsize *length,
991 GError **error)
993 g_return_val_if_fail (filename != NULL, FALSE);
994 g_return_val_if_fail (contents != NULL, FALSE);
996 *contents = NULL;
997 if (length)
998 *length = 0;
1000 #ifdef G_OS_WIN32
1001 return get_contents_win32 (filename, contents, length, error);
1002 #else
1003 return get_contents_posix (filename, contents, length, error);
1004 #endif
1007 static gboolean
1008 rename_file (const char *old_name,
1009 const char *new_name,
1010 GError **err)
1012 errno = 0;
1013 if (g_rename (old_name, new_name) == -1)
1015 int save_errno = errno;
1016 gchar *display_old_name = g_filename_display_name (old_name);
1017 gchar *display_new_name = g_filename_display_name (new_name);
1019 g_set_error (err,
1020 G_FILE_ERROR,
1021 g_file_error_from_errno (save_errno),
1022 _("Failed to rename file “%s” to “%s”: g_rename() failed: %s"),
1023 display_old_name,
1024 display_new_name,
1025 g_strerror (save_errno));
1027 g_free (display_old_name);
1028 g_free (display_new_name);
1030 return FALSE;
1033 return TRUE;
1036 static gchar *
1037 write_to_temp_file (const gchar *contents,
1038 gssize length,
1039 const gchar *dest_file,
1040 GError **err)
1042 gchar *tmp_name;
1043 gchar *retval;
1044 gint fd;
1046 retval = NULL;
1048 tmp_name = g_strdup_printf ("%s.XXXXXX", dest_file);
1050 errno = 0;
1051 fd = g_mkstemp_full (tmp_name, O_RDWR | O_BINARY, 0666);
1053 if (fd == -1)
1055 int saved_errno = errno;
1056 set_file_error (err,
1057 tmp_name, _("Failed to create file “%s”: %s"),
1058 saved_errno);
1059 goto out;
1062 #ifdef HAVE_FALLOCATE
1063 if (length > 0)
1065 /* We do this on a 'best effort' basis... It may not be supported
1066 * on the underlying filesystem.
1068 (void) fallocate (fd, 0, 0, length);
1070 #endif
1071 while (length > 0)
1073 gssize s;
1075 s = write (fd, contents, length);
1077 if (s < 0)
1079 int saved_errno = errno;
1080 if (saved_errno == EINTR)
1081 continue;
1083 set_file_error (err,
1084 tmp_name, _("Failed to write file “%s”: write() failed: %s"),
1085 saved_errno);
1086 close (fd);
1087 g_unlink (tmp_name);
1089 goto out;
1092 g_assert (s <= length);
1094 contents += s;
1095 length -= s;
1098 #ifdef BTRFS_SUPER_MAGIC
1100 struct statfs buf;
1102 /* On Linux, on btrfs, skip the fsync since rename-over-existing is
1103 * guaranteed to be atomic and this is the only case in which we
1104 * would fsync() anyway.
1107 if (fstatfs (fd, &buf) == 0 && buf.f_type == BTRFS_SUPER_MAGIC)
1108 goto no_fsync;
1110 #endif
1112 #ifdef HAVE_FSYNC
1114 struct stat statbuf;
1116 errno = 0;
1117 /* If the final destination exists and is > 0 bytes, we want to sync the
1118 * newly written file to ensure the data is on disk when we rename over
1119 * the destination. Otherwise if we get a system crash we can lose both
1120 * the new and the old file on some filesystems. (I.E. those that don't
1121 * guarantee the data is written to the disk before the metadata.)
1123 if (g_lstat (dest_file, &statbuf) == 0 && statbuf.st_size > 0 && fsync (fd) != 0)
1125 int saved_errno = errno;
1126 set_file_error (err,
1127 tmp_name, _("Failed to write file “%s”: fsync() failed: %s"),
1128 saved_errno);
1129 close (fd);
1130 g_unlink (tmp_name);
1132 goto out;
1135 #endif
1137 #ifdef BTRFS_SUPER_MAGIC
1138 no_fsync:
1139 #endif
1141 errno = 0;
1142 if (!g_close (fd, err))
1144 g_unlink (tmp_name);
1146 goto out;
1149 retval = g_strdup (tmp_name);
1151 out:
1152 g_free (tmp_name);
1154 return retval;
1158 * g_file_set_contents:
1159 * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1160 * encoding
1161 * @contents: (array length=length) (element-type guint8): string to write to the file
1162 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1163 * @error: return location for a #GError, or %NULL
1165 * Writes all of @contents to a file named @filename, with good error checking.
1166 * If a file called @filename already exists it will be overwritten.
1168 * This write is atomic in the sense that it is first written to a temporary
1169 * file which is then renamed to the final name. Notes:
1171 * - On UNIX, if @filename already exists hard links to @filename will break.
1172 * Also since the file is recreated, existing permissions, access control
1173 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1174 * the link itself will be replaced, not the linked file.
1176 * - On Windows renaming a file will not remove an existing file with the
1177 * new name, so on Windows there is a race condition between the existing
1178 * file being removed and the temporary file being renamed.
1180 * - On Windows there is no way to remove a file that is open to some
1181 * process, or mapped into memory. Thus, this function will fail if
1182 * @filename already exists and is open.
1184 * If the call was successful, it returns %TRUE. If the call was not successful,
1185 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1186 * Possible error codes are those in the #GFileError enumeration.
1188 * Note that the name for the temporary file is constructed by appending up
1189 * to 7 characters to @filename.
1191 * Returns: %TRUE on success, %FALSE if an error occurred
1193 * Since: 2.8
1195 gboolean
1196 g_file_set_contents (const gchar *filename,
1197 const gchar *contents,
1198 gssize length,
1199 GError **error)
1201 gchar *tmp_filename;
1202 gboolean retval;
1203 GError *rename_error = NULL;
1205 g_return_val_if_fail (filename != NULL, FALSE);
1206 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1207 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1208 g_return_val_if_fail (length >= -1, FALSE);
1210 if (length == -1)
1211 length = strlen (contents);
1213 tmp_filename = write_to_temp_file (contents, length, filename, error);
1215 if (!tmp_filename)
1217 retval = FALSE;
1218 goto out;
1221 if (!rename_file (tmp_filename, filename, &rename_error))
1223 #ifndef G_OS_WIN32
1225 g_unlink (tmp_filename);
1226 g_propagate_error (error, rename_error);
1227 retval = FALSE;
1228 goto out;
1230 #else /* G_OS_WIN32 */
1232 /* Renaming failed, but on Windows this may just mean
1233 * the file already exists. So if the target file
1234 * exists, try deleting it and do the rename again.
1236 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1238 g_unlink (tmp_filename);
1239 g_propagate_error (error, rename_error);
1240 retval = FALSE;
1241 goto out;
1244 g_error_free (rename_error);
1246 if (g_unlink (filename) == -1)
1248 int saved_errno = errno;
1249 set_file_error (error,
1250 filename,
1251 _("Existing file “%s” could not be removed: g_unlink() failed: %s"),
1252 saved_errno);
1253 g_unlink (tmp_filename);
1254 retval = FALSE;
1255 goto out;
1258 if (!rename_file (tmp_filename, filename, error))
1260 g_unlink (tmp_filename);
1261 retval = FALSE;
1262 goto out;
1265 #endif
1268 retval = TRUE;
1270 out:
1271 g_free (tmp_filename);
1272 return retval;
1276 * get_tmp_file based on the mkstemp implementation from the GNU C library.
1277 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1279 typedef gint (*GTmpFileCallback) (const gchar *, gint, gint);
1281 static gint
1282 get_tmp_file (gchar *tmpl,
1283 GTmpFileCallback f,
1284 int flags,
1285 int mode)
1287 char *XXXXXX;
1288 int count, fd;
1289 static const char letters[] =
1290 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1291 static const int NLETTERS = sizeof (letters) - 1;
1292 glong value;
1293 GTimeVal tv;
1294 static int counter = 0;
1296 g_return_val_if_fail (tmpl != NULL, -1);
1298 /* find the last occurrence of "XXXXXX" */
1299 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1301 if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1303 errno = EINVAL;
1304 return -1;
1307 /* Get some more or less random data. */
1308 g_get_current_time (&tv);
1309 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1311 for (count = 0; count < 100; value += 7777, ++count)
1313 glong v = value;
1315 /* Fill in the random bits. */
1316 XXXXXX[0] = letters[v % NLETTERS];
1317 v /= NLETTERS;
1318 XXXXXX[1] = letters[v % NLETTERS];
1319 v /= NLETTERS;
1320 XXXXXX[2] = letters[v % NLETTERS];
1321 v /= NLETTERS;
1322 XXXXXX[3] = letters[v % NLETTERS];
1323 v /= NLETTERS;
1324 XXXXXX[4] = letters[v % NLETTERS];
1325 v /= NLETTERS;
1326 XXXXXX[5] = letters[v % NLETTERS];
1328 fd = f (tmpl, flags, mode);
1330 if (fd >= 0)
1331 return fd;
1332 else if (errno != EEXIST)
1333 /* Any other error will apply also to other names we might
1334 * try, and there are 2^32 or so of them, so give up now.
1336 return -1;
1339 /* We got out of the loop because we ran out of combinations to try. */
1340 errno = EEXIST;
1341 return -1;
1344 /* Some GTmpFileCallback implementations.
1346 * Note: we cannot use open() or g_open() directly because even though
1347 * they appear compatible, they may be vararg functions and calling
1348 * varargs functions through a non-varargs type is undefined.
1350 static gint
1351 wrap_g_mkdir (const gchar *filename,
1352 int flags G_GNUC_UNUSED,
1353 int mode)
1355 /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1356 return g_mkdir (filename, mode);
1359 static gint
1360 wrap_g_open (const gchar *filename,
1361 int flags,
1362 int mode)
1364 return g_open (filename, flags, mode);
1368 * g_mkdtemp_full: (skip)
1369 * @tmpl: (type filename): template directory name
1370 * @mode: permissions to create the temporary directory with
1372 * Creates a temporary directory. See the mkdtemp() documentation
1373 * on most UNIX-like systems.
1375 * The parameter is a string that should follow the rules for
1376 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1377 * g_mkdtemp_full() is slightly more flexible than mkdtemp() in that the
1378 * sequence does not have to occur at the very end of the template
1379 * and you can pass a @mode. The X string will be modified to form
1380 * the name of a directory that didn't exist. The string should be
1381 * in the GLib file name encoding. Most importantly, on Windows it
1382 * should be in UTF-8.
1384 * If you are going to be creating a temporary directory inside the
1385 * directory returned by g_get_tmp_dir(), you might want to use
1386 * g_dir_make_tmp() instead.
1388 * Returns: (nullable) (type filename): A pointer to @tmpl, which has been
1389 * modified to hold the directory name. In case of errors, %NULL is
1390 * returned, and %errno will be set.
1392 * Since: 2.30
1394 gchar *
1395 g_mkdtemp_full (gchar *tmpl,
1396 gint mode)
1398 if (get_tmp_file (tmpl, wrap_g_mkdir, 0, mode) == -1)
1399 return NULL;
1400 else
1401 return tmpl;
1405 * g_mkdtemp: (skip)
1406 * @tmpl: (type filename): template directory name
1408 * Creates a temporary directory. See the mkdtemp() documentation
1409 * on most UNIX-like systems.
1411 * The parameter is a string that should follow the rules for
1412 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1413 * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1414 * sequence does not have to occur at the very end of the template.
1415 * The X string will be modified to form the name of a directory that
1416 * didn't exist.
1417 * The string should be in the GLib file name encoding. Most importantly,
1418 * on Windows it should be in UTF-8.
1420 * If you are going to be creating a temporary directory inside the
1421 * directory returned by g_get_tmp_dir(), you might want to use
1422 * g_dir_make_tmp() instead.
1424 * Returns: (nullable) (type filename): A pointer to @tmpl, which has been
1425 * modified to hold the directory name. In case of errors, %NULL is
1426 * returned and %errno will be set.
1428 * Since: 2.30
1430 gchar *
1431 g_mkdtemp (gchar *tmpl)
1433 return g_mkdtemp_full (tmpl, 0700);
1437 * g_mkstemp_full: (skip)
1438 * @tmpl: (type filename): template filename
1439 * @flags: flags to pass to an open() call in addition to O_EXCL
1440 * and O_CREAT, which are passed automatically
1441 * @mode: permissions to create the temporary file with
1443 * Opens a temporary file. See the mkstemp() documentation
1444 * on most UNIX-like systems.
1446 * The parameter is a string that should follow the rules for
1447 * mkstemp() templates, i.e. contain the string "XXXXXX".
1448 * g_mkstemp_full() is slightly more flexible than mkstemp()
1449 * in that the sequence does not have to occur at the very end of the
1450 * template and you can pass a @mode and additional @flags. The X
1451 * string will be modified to form the name of a file that didn't exist.
1452 * The string should be in the GLib file name encoding. Most importantly,
1453 * on Windows it should be in UTF-8.
1455 * Returns: A file handle (as from open()) to the file
1456 * opened for reading and writing. The file handle should be
1457 * closed with close(). In case of errors, -1 is returned
1458 * and %errno will be set.
1460 * Since: 2.22
1462 gint
1463 g_mkstemp_full (gchar *tmpl,
1464 gint flags,
1465 gint mode)
1467 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1468 return get_tmp_file (tmpl, wrap_g_open,
1469 flags | O_CREAT | O_EXCL, mode);
1473 * g_mkstemp: (skip)
1474 * @tmpl: (type filename): template filename
1476 * Opens a temporary file. See the mkstemp() documentation
1477 * on most UNIX-like systems.
1479 * The parameter is a string that should follow the rules for
1480 * mkstemp() templates, i.e. contain the string "XXXXXX".
1481 * g_mkstemp() is slightly more flexible than mkstemp() in that the
1482 * sequence does not have to occur at the very end of the template.
1483 * The X string will be modified to form the name of a file that
1484 * didn't exist. The string should be in the GLib file name encoding.
1485 * Most importantly, on Windows it should be in UTF-8.
1487 * Returns: A file handle (as from open()) to the file
1488 * opened for reading and writing. The file is opened in binary
1489 * mode on platforms where there is a difference. The file handle
1490 * should be closed with close(). In case of errors, -1 is
1491 * returned and %errno will be set.
1493 gint
1494 g_mkstemp (gchar *tmpl)
1496 return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1499 static gint
1500 g_get_tmp_name (const gchar *tmpl,
1501 gchar **name_used,
1502 GTmpFileCallback f,
1503 gint flags,
1504 gint mode,
1505 GError **error)
1507 int retval;
1508 const char *tmpdir;
1509 const char *sep;
1510 char *fulltemplate;
1511 const char *slash;
1513 if (tmpl == NULL)
1514 tmpl = ".XXXXXX";
1516 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1517 #ifdef G_OS_WIN32
1518 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1519 #endif
1522 gchar *display_tmpl = g_filename_display_name (tmpl);
1523 char c[2];
1524 c[0] = *slash;
1525 c[1] = '\0';
1527 g_set_error (error,
1528 G_FILE_ERROR,
1529 G_FILE_ERROR_FAILED,
1530 _("Template “%s” invalid, should not contain a “%s”"),
1531 display_tmpl, c);
1532 g_free (display_tmpl);
1534 return -1;
1537 if (strstr (tmpl, "XXXXXX") == NULL)
1539 gchar *display_tmpl = g_filename_display_name (tmpl);
1540 g_set_error (error,
1541 G_FILE_ERROR,
1542 G_FILE_ERROR_FAILED,
1543 _("Template “%s” doesn’t contain XXXXXX"),
1544 display_tmpl);
1545 g_free (display_tmpl);
1546 return -1;
1549 tmpdir = g_get_tmp_dir ();
1551 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1552 sep = "";
1553 else
1554 sep = G_DIR_SEPARATOR_S;
1556 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1558 retval = get_tmp_file (fulltemplate, f, flags, mode);
1559 if (retval == -1)
1561 int saved_errno = errno;
1562 set_file_error (error,
1563 fulltemplate,
1564 _("Failed to create file “%s”: %s"),
1565 saved_errno);
1566 g_free (fulltemplate);
1567 return -1;
1570 *name_used = fulltemplate;
1572 return retval;
1576 * g_file_open_tmp:
1577 * @tmpl: (type filename) (nullable): Template for file name, as in
1578 * g_mkstemp(), basename only, or %NULL for a default template
1579 * @name_used: (out) (type filename): location to store actual name used,
1580 * or %NULL
1581 * @error: return location for a #GError
1583 * Opens a file for writing in the preferred directory for temporary
1584 * files (as returned by g_get_tmp_dir()).
1586 * @tmpl should be a string in the GLib file name encoding containing
1587 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1588 * However, unlike these functions, the template should only be a
1589 * basename, no directory components are allowed. If template is
1590 * %NULL, a default template is used.
1592 * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
1593 * modified, and might thus be a read-only literal string.
1595 * Upon success, and if @name_used is non-%NULL, the actual name used
1596 * is returned in @name_used. This string should be freed with g_free()
1597 * when not needed any longer. The returned name is in the GLib file
1598 * name encoding.
1600 * Returns: A file handle (as from open()) to the file opened for
1601 * reading and writing. The file is opened in binary mode on platforms
1602 * where there is a difference. The file handle should be closed with
1603 * close(). In case of errors, -1 is returned and @error will be set.
1605 gint
1606 g_file_open_tmp (const gchar *tmpl,
1607 gchar **name_used,
1608 GError **error)
1610 gchar *fulltemplate;
1611 gint result;
1613 g_return_val_if_fail (error == NULL || *error == NULL, -1);
1615 result = g_get_tmp_name (tmpl, &fulltemplate,
1616 wrap_g_open,
1617 O_CREAT | O_EXCL | O_RDWR | O_BINARY,
1618 0600,
1619 error);
1620 if (result != -1)
1622 if (name_used)
1623 *name_used = fulltemplate;
1624 else
1625 g_free (fulltemplate);
1628 return result;
1632 * g_dir_make_tmp:
1633 * @tmpl: (type filename) (nullable): Template for directory name,
1634 * as in g_mkdtemp(), basename only, or %NULL for a default template
1635 * @error: return location for a #GError
1637 * Creates a subdirectory in the preferred directory for temporary
1638 * files (as returned by g_get_tmp_dir()).
1640 * @tmpl should be a string in the GLib file name encoding containing
1641 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1642 * However, unlike these functions, the template should only be a
1643 * basename, no directory components are allowed. If template is
1644 * %NULL, a default template is used.
1646 * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
1647 * modified, and might thus be a read-only literal string.
1649 * Returns: (type filename): The actual name used. This string
1650 * should be freed with g_free() when not needed any longer and is
1651 * is in the GLib file name encoding. In case of errors, %NULL is
1652 * returned and @error will be set.
1654 * Since: 2.30
1656 gchar *
1657 g_dir_make_tmp (const gchar *tmpl,
1658 GError **error)
1660 gchar *fulltemplate;
1662 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1664 if (g_get_tmp_name (tmpl, &fulltemplate, wrap_g_mkdir, 0, 0700, error) == -1)
1665 return NULL;
1666 else
1667 return fulltemplate;
1670 static gchar *
1671 g_build_path_va (const gchar *separator,
1672 const gchar *first_element,
1673 va_list *args,
1674 gchar **str_array)
1676 GString *result;
1677 gint separator_len = strlen (separator);
1678 gboolean is_first = TRUE;
1679 gboolean have_leading = FALSE;
1680 const gchar *single_element = NULL;
1681 const gchar *next_element;
1682 const gchar *last_trailing = NULL;
1683 gint i = 0;
1685 result = g_string_new (NULL);
1687 if (str_array)
1688 next_element = str_array[i++];
1689 else
1690 next_element = first_element;
1692 while (TRUE)
1694 const gchar *element;
1695 const gchar *start;
1696 const gchar *end;
1698 if (next_element)
1700 element = next_element;
1701 if (str_array)
1702 next_element = str_array[i++];
1703 else
1704 next_element = va_arg (*args, gchar *);
1706 else
1707 break;
1709 /* Ignore empty elements */
1710 if (!*element)
1711 continue;
1713 start = element;
1715 if (separator_len)
1717 while (strncmp (start, separator, separator_len) == 0)
1718 start += separator_len;
1721 end = start + strlen (start);
1723 if (separator_len)
1725 while (end >= start + separator_len &&
1726 strncmp (end - separator_len, separator, separator_len) == 0)
1727 end -= separator_len;
1729 last_trailing = end;
1730 while (last_trailing >= element + separator_len &&
1731 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1732 last_trailing -= separator_len;
1734 if (!have_leading)
1736 /* If the leading and trailing separator strings are in the
1737 * same element and overlap, the result is exactly that element
1739 if (last_trailing <= start)
1740 single_element = element;
1742 g_string_append_len (result, element, start - element);
1743 have_leading = TRUE;
1745 else
1746 single_element = NULL;
1749 if (end == start)
1750 continue;
1752 if (!is_first)
1753 g_string_append (result, separator);
1755 g_string_append_len (result, start, end - start);
1756 is_first = FALSE;
1759 if (single_element)
1761 g_string_free (result, TRUE);
1762 return g_strdup (single_element);
1764 else
1766 if (last_trailing)
1767 g_string_append (result, last_trailing);
1769 return g_string_free (result, FALSE);
1774 * g_build_pathv:
1775 * @separator: a string used to separator the elements of the path.
1776 * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
1777 * array of strings containing the path elements.
1779 * Behaves exactly like g_build_path(), but takes the path elements
1780 * as a string array, instead of varargs. This function is mainly
1781 * meant for language bindings.
1783 * Returns: (type filename): a newly-allocated string that must be freed
1784 * with g_free().
1786 * Since: 2.8
1788 gchar *
1789 g_build_pathv (const gchar *separator,
1790 gchar **args)
1792 if (!args)
1793 return NULL;
1795 return g_build_path_va (separator, NULL, NULL, args);
1800 * g_build_path:
1801 * @separator: (type filename): a string used to separator the elements of the path.
1802 * @first_element: (type filename): the first element in the path
1803 * @...: remaining elements in path, terminated by %NULL
1805 * Creates a path from a series of elements using @separator as the
1806 * separator between elements. At the boundary between two elements,
1807 * any trailing occurrences of separator in the first element, or
1808 * leading occurrences of separator in the second element are removed
1809 * and exactly one copy of the separator is inserted.
1811 * Empty elements are ignored.
1813 * The number of leading copies of the separator on the result is
1814 * the same as the number of leading copies of the separator on
1815 * the first non-empty element.
1817 * The number of trailing copies of the separator on the result is
1818 * the same as the number of trailing copies of the separator on
1819 * the last non-empty element. (Determination of the number of
1820 * trailing copies is done without stripping leading copies, so
1821 * if the separator is `ABA`, then `ABABA` has 1 trailing copy.)
1823 * However, if there is only a single non-empty element, and there
1824 * are no characters in that element not part of the leading or
1825 * trailing separators, then the result is exactly the original value
1826 * of that element.
1828 * Other than for determination of the number of leading and trailing
1829 * copies of the separator, elements consisting only of copies
1830 * of the separator are ignored.
1832 * Returns: (type filename): a newly-allocated string that must be freed with
1833 * g_free().
1835 gchar *
1836 g_build_path (const gchar *separator,
1837 const gchar *first_element,
1838 ...)
1840 gchar *str;
1841 va_list args;
1843 g_return_val_if_fail (separator != NULL, NULL);
1845 va_start (args, first_element);
1846 str = g_build_path_va (separator, first_element, &args, NULL);
1847 va_end (args);
1849 return str;
1852 #ifdef G_OS_WIN32
1854 static gchar *
1855 g_build_pathname_va (const gchar *first_element,
1856 va_list *args,
1857 gchar **str_array)
1859 /* Code copied from g_build_pathv(), and modified to use two
1860 * alternative single-character separators.
1862 GString *result;
1863 gboolean is_first = TRUE;
1864 gboolean have_leading = FALSE;
1865 const gchar *single_element = NULL;
1866 const gchar *next_element;
1867 const gchar *last_trailing = NULL;
1868 gchar current_separator = '\\';
1869 gint i = 0;
1871 result = g_string_new (NULL);
1873 if (str_array)
1874 next_element = str_array[i++];
1875 else
1876 next_element = first_element;
1878 while (TRUE)
1880 const gchar *element;
1881 const gchar *start;
1882 const gchar *end;
1884 if (next_element)
1886 element = next_element;
1887 if (str_array)
1888 next_element = str_array[i++];
1889 else
1890 next_element = va_arg (*args, gchar *);
1892 else
1893 break;
1895 /* Ignore empty elements */
1896 if (!*element)
1897 continue;
1899 start = element;
1901 if (TRUE)
1903 while (start &&
1904 (*start == '\\' || *start == '/'))
1906 current_separator = *start;
1907 start++;
1911 end = start + strlen (start);
1913 if (TRUE)
1915 while (end >= start + 1 &&
1916 (end[-1] == '\\' || end[-1] == '/'))
1918 current_separator = end[-1];
1919 end--;
1922 last_trailing = end;
1923 while (last_trailing >= element + 1 &&
1924 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1925 last_trailing--;
1927 if (!have_leading)
1929 /* If the leading and trailing separator strings are in the
1930 * same element and overlap, the result is exactly that element
1932 if (last_trailing <= start)
1933 single_element = element;
1935 g_string_append_len (result, element, start - element);
1936 have_leading = TRUE;
1938 else
1939 single_element = NULL;
1942 if (end == start)
1943 continue;
1945 if (!is_first)
1946 g_string_append_len (result, &current_separator, 1);
1948 g_string_append_len (result, start, end - start);
1949 is_first = FALSE;
1952 if (single_element)
1954 g_string_free (result, TRUE);
1955 return g_strdup (single_element);
1957 else
1959 if (last_trailing)
1960 g_string_append (result, last_trailing);
1962 return g_string_free (result, FALSE);
1966 #endif
1968 static gchar *
1969 g_build_filename_va (const gchar *first_argument,
1970 va_list *args,
1971 gchar **str_array)
1973 gchar *str;
1975 #ifndef G_OS_WIN32
1976 str = g_build_path_va (G_DIR_SEPARATOR_S, first_argument, args, str_array);
1977 #else
1978 str = g_build_pathname_va (first_argument, args, str_array);
1979 #endif
1981 return str;
1985 * g_build_filename_valist:
1986 * @first_element: (type filename): the first element in the path
1987 * @args: va_list of remaining elements in path
1989 * Behaves exactly like g_build_filename(), but takes the path elements
1990 * as a va_list. This function is mainly meant for language bindings.
1992 * Returns: (type filename): a newly-allocated string that must be freed
1993 * with g_free().
1995 * Since: 2.56
1997 gchar *
1998 g_build_filename_valist (const gchar *first_element,
1999 va_list *args)
2001 g_return_val_if_fail (first_element != NULL, NULL);
2003 return g_build_filename_va (first_element, args, NULL);
2007 * g_build_filenamev:
2008 * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
2009 * array of strings containing the path elements.
2011 * Behaves exactly like g_build_filename(), but takes the path elements
2012 * as a string array, instead of varargs. This function is mainly
2013 * meant for language bindings.
2015 * Returns: (type filename): a newly-allocated string that must be freed
2016 * with g_free().
2018 * Since: 2.8
2020 gchar *
2021 g_build_filenamev (gchar **args)
2023 return g_build_filename_va (NULL, NULL, args);
2027 * g_build_filename:
2028 * @first_element: (type filename): the first element in the path
2029 * @...: remaining elements in path, terminated by %NULL
2031 * Creates a filename from a series of elements using the correct
2032 * separator for filenames.
2034 * On Unix, this function behaves identically to `g_build_path
2035 * (G_DIR_SEPARATOR_S, first_element, ....)`.
2037 * On Windows, it takes into account that either the backslash
2038 * (`\` or slash (`/`) can be used as separator in filenames, but
2039 * otherwise behaves as on UNIX. When file pathname separators need
2040 * to be inserted, the one that last previously occurred in the
2041 * parameters (reading from left to right) is used.
2043 * No attempt is made to force the resulting filename to be an absolute
2044 * path. If the first element is a relative path, the result will
2045 * be a relative path.
2047 * Returns: (type filename): a newly-allocated string that must be freed with
2048 * g_free().
2050 gchar *
2051 g_build_filename (const gchar *first_element,
2052 ...)
2054 gchar *str;
2055 va_list args;
2057 va_start (args, first_element);
2058 str = g_build_filename_va (first_element, &args, NULL);
2059 va_end (args);
2061 return str;
2065 * g_file_read_link:
2066 * @filename: (type filename): the symbolic link
2067 * @error: return location for a #GError
2069 * Reads the contents of the symbolic link @filename like the POSIX
2070 * readlink() function. The returned string is in the encoding used
2071 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
2073 * Returns: (type filename): A newly-allocated string with the contents of
2074 * the symbolic link, or %NULL if an error occurred.
2076 * Since: 2.4
2078 gchar *
2079 g_file_read_link (const gchar *filename,
2080 GError **error)
2082 #if defined (HAVE_READLINK) || defined (G_OS_WIN32)
2083 gchar *buffer;
2084 size_t size;
2085 gssize read_size;
2087 g_return_val_if_fail (filename != NULL, NULL);
2088 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2090 size = 256;
2091 buffer = g_malloc (size);
2093 while (TRUE)
2095 #ifndef G_OS_WIN32
2096 read_size = readlink (filename, buffer, size);
2097 #else
2098 read_size = g_win32_readlink_utf8 (filename, buffer, size);
2099 #endif
2100 if (read_size < 0)
2102 int saved_errno = errno;
2103 set_file_error (error,
2104 filename,
2105 _("Failed to read the symbolic link “%s”: %s"),
2106 saved_errno);
2107 g_free (buffer);
2108 return NULL;
2111 if ((size_t) read_size < size)
2113 buffer[read_size] = 0;
2114 return buffer;
2117 size *= 2;
2118 buffer = g_realloc (buffer, size);
2120 #else
2121 g_return_val_if_fail (filename != NULL, NULL);
2122 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2124 g_set_error_literal (error,
2125 G_FILE_ERROR,
2126 G_FILE_ERROR_INVAL,
2127 _("Symbolic links not supported"));
2129 return NULL;
2130 #endif
2134 * g_path_is_absolute:
2135 * @file_name: (type filename): a file name
2137 * Returns %TRUE if the given @file_name is an absolute file name.
2138 * Note that this is a somewhat vague concept on Windows.
2140 * On POSIX systems, an absolute file name is well-defined. It always
2141 * starts from the single root directory. For example "/usr/local".
2143 * On Windows, the concepts of current drive and drive-specific
2144 * current directory introduce vagueness. This function interprets as
2145 * an absolute file name one that either begins with a directory
2146 * separator such as "\Users\tml" or begins with the root on a drive,
2147 * for example "C:\Windows". The first case also includes UNC paths
2148 * such as "\\\\myserver\docs\foo". In all cases, either slashes or
2149 * backslashes are accepted.
2151 * Note that a file name relative to the current drive root does not
2152 * truly specify a file uniquely over time and across processes, as
2153 * the current drive is a per-process value and can be changed.
2155 * File names relative the current directory on some specific drive,
2156 * such as "D:foo/bar", are not interpreted as absolute by this
2157 * function, but they obviously are not relative to the normal current
2158 * directory as returned by getcwd() or g_get_current_dir()
2159 * either. Such paths should be avoided, or need to be handled using
2160 * Windows-specific code.
2162 * Returns: %TRUE if @file_name is absolute
2164 gboolean
2165 g_path_is_absolute (const gchar *file_name)
2167 g_return_val_if_fail (file_name != NULL, FALSE);
2169 if (G_IS_DIR_SEPARATOR (file_name[0]))
2170 return TRUE;
2172 #ifdef G_OS_WIN32
2173 /* Recognize drive letter on native Windows */
2174 if (g_ascii_isalpha (file_name[0]) &&
2175 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
2176 return TRUE;
2177 #endif
2179 return FALSE;
2183 * g_path_skip_root:
2184 * @file_name: (type filename): a file name
2186 * Returns a pointer into @file_name after the root component,
2187 * i.e. after the "/" in UNIX or "C:\" under Windows. If @file_name
2188 * is not an absolute path it returns %NULL.
2190 * Returns: (type filename) (nullable): a pointer into @file_name after the
2191 * root component
2193 const gchar *
2194 g_path_skip_root (const gchar *file_name)
2196 g_return_val_if_fail (file_name != NULL, NULL);
2198 #ifdef G_PLATFORM_WIN32
2199 /* Skip \\server\share or //server/share */
2200 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2201 G_IS_DIR_SEPARATOR (file_name[1]) &&
2202 file_name[2] &&
2203 !G_IS_DIR_SEPARATOR (file_name[2]))
2205 gchar *p;
2206 p = strchr (file_name + 2, G_DIR_SEPARATOR);
2208 #ifdef G_OS_WIN32
2210 gchar *q;
2212 q = strchr (file_name + 2, '/');
2213 if (p == NULL || (q != NULL && q < p))
2214 p = q;
2216 #endif
2218 if (p && p > file_name + 2 && p[1])
2220 file_name = p + 1;
2222 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
2223 file_name++;
2225 /* Possibly skip a backslash after the share name */
2226 if (G_IS_DIR_SEPARATOR (file_name[0]))
2227 file_name++;
2229 return (gchar *)file_name;
2232 #endif
2234 /* Skip initial slashes */
2235 if (G_IS_DIR_SEPARATOR (file_name[0]))
2237 while (G_IS_DIR_SEPARATOR (file_name[0]))
2238 file_name++;
2239 return (gchar *)file_name;
2242 #ifdef G_OS_WIN32
2243 /* Skip X:\ */
2244 if (g_ascii_isalpha (file_name[0]) &&
2245 file_name[1] == ':' &&
2246 G_IS_DIR_SEPARATOR (file_name[2]))
2247 return (gchar *)file_name + 3;
2248 #endif
2250 return NULL;
2254 * g_basename:
2255 * @file_name: (type filename): the name of the file
2257 * Gets the name of the file without any leading directory
2258 * components. It returns a pointer into the given file name
2259 * string.
2261 * Returns: (type filename): the name of the file without any leading
2262 * directory components
2264 * Deprecated:2.2: Use g_path_get_basename() instead, but notice
2265 * that g_path_get_basename() allocates new memory for the
2266 * returned string, unlike this function which returns a pointer
2267 * into the argument.
2269 const gchar *
2270 g_basename (const gchar *file_name)
2272 gchar *base;
2274 g_return_val_if_fail (file_name != NULL, NULL);
2276 base = strrchr (file_name, G_DIR_SEPARATOR);
2278 #ifdef G_OS_WIN32
2280 gchar *q;
2281 q = strrchr (file_name, '/');
2282 if (base == NULL || (q != NULL && q > base))
2283 base = q;
2285 #endif
2287 if (base)
2288 return base + 1;
2290 #ifdef G_OS_WIN32
2291 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2292 return (gchar*) file_name + 2;
2293 #endif
2295 return (gchar*) file_name;
2299 * g_path_get_basename:
2300 * @file_name: (type filename): the name of the file
2302 * Gets the last component of the filename.
2304 * If @file_name ends with a directory separator it gets the component
2305 * before the last slash. If @file_name consists only of directory
2306 * separators (and on Windows, possibly a drive letter), a single
2307 * separator is returned. If @file_name is empty, it gets ".".
2309 * Returns: (type filename): a newly allocated string containing the last
2310 * component of the filename
2312 gchar *
2313 g_path_get_basename (const gchar *file_name)
2315 gssize base;
2316 gssize last_nonslash;
2317 gsize len;
2318 gchar *retval;
2320 g_return_val_if_fail (file_name != NULL, NULL);
2322 if (file_name[0] == '\0')
2323 return g_strdup (".");
2325 last_nonslash = strlen (file_name) - 1;
2327 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
2328 last_nonslash--;
2330 if (last_nonslash == -1)
2331 /* string only containing slashes */
2332 return g_strdup (G_DIR_SEPARATOR_S);
2334 #ifdef G_OS_WIN32
2335 if (last_nonslash == 1 &&
2336 g_ascii_isalpha (file_name[0]) &&
2337 file_name[1] == ':')
2338 /* string only containing slashes and a drive */
2339 return g_strdup (G_DIR_SEPARATOR_S);
2340 #endif
2341 base = last_nonslash;
2343 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
2344 base--;
2346 #ifdef G_OS_WIN32
2347 if (base == -1 &&
2348 g_ascii_isalpha (file_name[0]) &&
2349 file_name[1] == ':')
2350 base = 1;
2351 #endif /* G_OS_WIN32 */
2353 len = last_nonslash - base;
2354 retval = g_malloc (len + 1);
2355 memcpy (retval, file_name + base + 1, len);
2356 retval [len] = '\0';
2358 return retval;
2362 * g_dirname:
2363 * @file_name: (type filename): the name of the file
2365 * Gets the directory components of a file name.
2367 * If the file name has no directory components "." is returned.
2368 * The returned string should be freed when no longer needed.
2370 * Returns: (type filename): the directory components of the file
2372 * Deprecated: use g_path_get_dirname() instead
2376 * g_path_get_dirname:
2377 * @file_name: (type filename): the name of the file
2379 * Gets the directory components of a file name.
2381 * If the file name has no directory components "." is returned.
2382 * The returned string should be freed when no longer needed.
2384 * Returns: (type filename): the directory components of the file
2386 gchar *
2387 g_path_get_dirname (const gchar *file_name)
2389 gchar *base;
2390 gsize len;
2392 g_return_val_if_fail (file_name != NULL, NULL);
2394 base = strrchr (file_name, G_DIR_SEPARATOR);
2396 #ifdef G_OS_WIN32
2398 gchar *q;
2399 q = strrchr (file_name, '/');
2400 if (base == NULL || (q != NULL && q > base))
2401 base = q;
2403 #endif
2405 if (!base)
2407 #ifdef G_OS_WIN32
2408 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2410 gchar drive_colon_dot[4];
2412 drive_colon_dot[0] = file_name[0];
2413 drive_colon_dot[1] = ':';
2414 drive_colon_dot[2] = '.';
2415 drive_colon_dot[3] = '\0';
2417 return g_strdup (drive_colon_dot);
2419 #endif
2420 return g_strdup (".");
2423 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
2424 base--;
2426 #ifdef G_OS_WIN32
2427 /* base points to the char before the last slash.
2429 * In case file_name is the root of a drive (X:\) or a child of the
2430 * root of a drive (X:\foo), include the slash.
2432 * In case file_name is the root share of an UNC path
2433 * (\\server\share), add a slash, returning \\server\share\ .
2435 * In case file_name is a direct child of a share in an UNC path
2436 * (\\server\share\foo), include the slash after the share name,
2437 * returning \\server\share\ .
2439 if (base == file_name + 1 &&
2440 g_ascii_isalpha (file_name[0]) &&
2441 file_name[1] == ':')
2442 base++;
2443 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2444 G_IS_DIR_SEPARATOR (file_name[1]) &&
2445 file_name[2] &&
2446 !G_IS_DIR_SEPARATOR (file_name[2]) &&
2447 base >= file_name + 2)
2449 const gchar *p = file_name + 2;
2450 while (*p && !G_IS_DIR_SEPARATOR (*p))
2451 p++;
2452 if (p == base + 1)
2454 len = (guint) strlen (file_name) + 1;
2455 base = g_new (gchar, len + 1);
2456 strcpy (base, file_name);
2457 base[len-1] = G_DIR_SEPARATOR;
2458 base[len] = 0;
2459 return base;
2461 if (G_IS_DIR_SEPARATOR (*p))
2463 p++;
2464 while (*p && !G_IS_DIR_SEPARATOR (*p))
2465 p++;
2466 if (p == base + 1)
2467 base++;
2470 #endif
2472 len = (guint) 1 + base - file_name;
2473 base = g_new (gchar, len + 1);
2474 memmove (base, file_name, len);
2475 base[len] = 0;
2477 return base;
2481 * g_canonicalize_filename:
2482 * @filename: (type filename): the name of the file
2483 * @relative_to: (type filename) (nullable): the relative directory, or %NULL
2484 * to use the current working directory
2486 * Gets the canonical file name from @filename. All triple slashes are turned into
2487 * single slashes, and all `..` and `.`s resolved against @relative_to.
2489 * Symlinks are not followed, and the returned path is guaranteed to be absolute.
2491 * If @filename is an absolute path, @relative_to is ignored. Otherwise,
2492 * @relative_to will be prepended to @filename to make it absolute. @relative_to
2493 * must be an absolute path, or %NULL. If @relative_to is %NULL, it'll fallback
2494 * to g_get_current_dir().
2496 * This function never fails, and will canonicalize file paths even if they don't
2497 * exist.
2499 * No file system I/O is done.
2501 * Returns: (type filename) (transfer full): a newly allocated string with the
2502 * canonical file path
2503 * Since: 2.58
2505 gchar *
2506 g_canonicalize_filename (const gchar *filename,
2507 const gchar *relative_to)
2509 gchar *canon, *start, *p, *q;
2510 guint i;
2512 g_return_val_if_fail (relative_to == NULL || g_path_is_absolute (relative_to), NULL);
2514 if (!g_path_is_absolute (filename))
2516 gchar *cwd_allocated = NULL;
2517 const gchar *cwd;
2519 if (relative_to != NULL)
2520 cwd = relative_to;
2521 else
2522 cwd = cwd_allocated = g_get_current_dir ();
2524 canon = g_build_filename (cwd, filename, NULL);
2525 g_free (cwd_allocated);
2527 else
2529 canon = g_strdup (filename);
2532 start = (char *)g_path_skip_root (canon);
2534 if (start == NULL)
2536 /* This shouldn't really happen, as g_get_current_dir() should
2537 return an absolute pathname, but bug 573843 shows this is
2538 not always happening */
2539 g_free (canon);
2540 return g_build_filename (G_DIR_SEPARATOR_S, filename, NULL);
2543 /* POSIX allows double slashes at the start to
2544 * mean something special (as does windows too).
2545 * So, "//" != "/", but more than two slashes
2546 * is treated as "/".
2548 i = 0;
2549 for (p = start - 1;
2550 (p >= canon) &&
2551 G_IS_DIR_SEPARATOR (*p);
2552 p--)
2553 i++;
2554 if (i > 2)
2556 i -= 1;
2557 start -= i;
2558 memmove (start, start+i, strlen (start+i) + 1);
2561 /* Make sure we're using the canonical dir separator */
2562 p++;
2563 while (p < start && G_IS_DIR_SEPARATOR (*p))
2564 *p++ = G_DIR_SEPARATOR;
2566 p = start;
2567 while (*p != 0)
2569 if (p[0] == '.' && (p[1] == 0 || G_IS_DIR_SEPARATOR (p[1])))
2571 memmove (p, p+1, strlen (p+1)+1);
2573 else if (p[0] == '.' && p[1] == '.' && (p[2] == 0 || G_IS_DIR_SEPARATOR (p[2])))
2575 q = p + 2;
2576 /* Skip previous separator */
2577 p = p - 2;
2578 if (p < start)
2579 p = start;
2580 while (p > start && !G_IS_DIR_SEPARATOR (*p))
2581 p--;
2582 if (G_IS_DIR_SEPARATOR (*p))
2583 *p++ = G_DIR_SEPARATOR;
2584 memmove (p, q, strlen (q)+1);
2586 else
2588 /* Skip until next separator */
2589 while (*p != 0 && !G_IS_DIR_SEPARATOR (*p))
2590 p++;
2592 if (*p != 0)
2594 /* Canonicalize one separator */
2595 *p++ = G_DIR_SEPARATOR;
2599 /* Remove additional separators */
2600 q = p;
2601 while (*q && G_IS_DIR_SEPARATOR (*q))
2602 q++;
2604 if (p != q)
2605 memmove (p, q, strlen (q) + 1);
2608 /* Remove trailing slashes */
2609 if (p > start && G_IS_DIR_SEPARATOR (*(p-1)))
2610 *(p-1) = 0;
2612 return canon;
2615 #if defined(MAXPATHLEN)
2616 #define G_PATH_LENGTH MAXPATHLEN
2617 #elif defined(PATH_MAX)
2618 #define G_PATH_LENGTH PATH_MAX
2619 #elif defined(_PC_PATH_MAX)
2620 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
2621 #else
2622 #define G_PATH_LENGTH 2048
2623 #endif
2626 * g_get_current_dir:
2628 * Gets the current directory.
2630 * The returned string should be freed when no longer needed.
2631 * The encoding of the returned string is system defined.
2632 * On Windows, it is always UTF-8.
2634 * Since GLib 2.40, this function will return the value of the "PWD"
2635 * environment variable if it is set and it happens to be the same as
2636 * the current directory. This can make a difference in the case that
2637 * the current directory is the target of a symbolic link.
2639 * Returns: (type filename): the current directory
2641 gchar *
2642 g_get_current_dir (void)
2644 #ifdef G_OS_WIN32
2646 gchar *dir = NULL;
2647 wchar_t dummy[2], *wdir;
2648 int len;
2650 len = GetCurrentDirectoryW (2, dummy);
2651 wdir = g_new (wchar_t, len);
2653 if (GetCurrentDirectoryW (len, wdir) == len - 1)
2654 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
2656 g_free (wdir);
2658 if (dir == NULL)
2659 dir = g_strdup ("\\");
2661 return dir;
2663 #else
2664 const gchar *pwd;
2665 gchar *buffer = NULL;
2666 gchar *dir = NULL;
2667 static gulong max_len = 0;
2668 struct stat pwdbuf, dotbuf;
2670 pwd = g_getenv ("PWD");
2671 if (pwd != NULL &&
2672 g_stat (".", &dotbuf) == 0 && g_stat (pwd, &pwdbuf) == 0 &&
2673 dotbuf.st_dev == pwdbuf.st_dev && dotbuf.st_ino == pwdbuf.st_ino)
2674 return g_strdup (pwd);
2676 if (max_len == 0)
2677 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
2679 while (max_len < G_MAXULONG / 2)
2681 g_free (buffer);
2682 buffer = g_new (gchar, max_len + 1);
2683 *buffer = 0;
2684 dir = getcwd (buffer, max_len);
2686 if (dir || errno != ERANGE)
2687 break;
2689 max_len *= 2;
2692 if (!dir || !*buffer)
2694 /* hm, should we g_error() out here?
2695 * this can happen if e.g. "./" has mode \0000
2697 buffer[0] = G_DIR_SEPARATOR;
2698 buffer[1] = 0;
2701 dir = g_strdup (buffer);
2702 g_free (buffer);
2704 return dir;
2706 #endif /* !G_OS_WIN32 */
2709 #ifdef G_OS_WIN32
2711 /* Binary compatibility versions. Not for newly compiled code. */
2713 _GLIB_EXTERN gboolean g_file_test_utf8 (const gchar *filename,
2714 GFileTest test);
2715 _GLIB_EXTERN gboolean g_file_get_contents_utf8 (const gchar *filename,
2716 gchar **contents,
2717 gsize *length,
2718 GError **error);
2719 _GLIB_EXTERN gint g_mkstemp_utf8 (gchar *tmpl);
2720 _GLIB_EXTERN gint g_file_open_tmp_utf8 (const gchar *tmpl,
2721 gchar **name_used,
2722 GError **error);
2723 _GLIB_EXTERN gchar *g_get_current_dir_utf8 (void);
2726 gboolean
2727 g_file_test_utf8 (const gchar *filename,
2728 GFileTest test)
2730 return g_file_test (filename, test);
2733 gboolean
2734 g_file_get_contents_utf8 (const gchar *filename,
2735 gchar **contents,
2736 gsize *length,
2737 GError **error)
2739 return g_file_get_contents (filename, contents, length, error);
2742 gint
2743 g_mkstemp_utf8 (gchar *tmpl)
2745 return g_mkstemp (tmpl);
2748 gint
2749 g_file_open_tmp_utf8 (const gchar *tmpl,
2750 gchar **name_used,
2751 GError **error)
2753 return g_file_open_tmp (tmpl, name_used, error);
2756 gchar *
2757 g_get_current_dir_utf8 (void)
2759 return g_get_current_dir ();
2762 #endif