tests: Fix leak when checking for du binary
[glib.git] / glib / gfileutils.c
blob1e7a771a94421d16ac0da3aaef79393e9c12e959
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 UNIX, if @filename already exists and is non-empty, and if the system
1177 * supports it (via a journalling filesystem or equivalent), the fsync()
1178 * call (or equivalent) will be used to ensure atomic replacement: @filename
1179 * will contain either its old contents or @contents, even in the face of
1180 * system power loss, the disk being unsafely removed, etc.
1182 * - On UNIX, if @filename does not already exist or is empty, there is a
1183 * possibility that system power loss etc. after calling this function will
1184 * leave @filename empty or full of NUL bytes, depending on the underlying
1185 * filesystem.
1187 * - On Windows renaming a file will not remove an existing file with the
1188 * new name, so on Windows there is a race condition between the existing
1189 * file being removed and the temporary file being renamed.
1191 * - On Windows there is no way to remove a file that is open to some
1192 * process, or mapped into memory. Thus, this function will fail if
1193 * @filename already exists and is open.
1195 * If the call was successful, it returns %TRUE. If the call was not successful,
1196 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1197 * Possible error codes are those in the #GFileError enumeration.
1199 * Note that the name for the temporary file is constructed by appending up
1200 * to 7 characters to @filename.
1202 * Returns: %TRUE on success, %FALSE if an error occurred
1204 * Since: 2.8
1206 gboolean
1207 g_file_set_contents (const gchar *filename,
1208 const gchar *contents,
1209 gssize length,
1210 GError **error)
1212 gchar *tmp_filename;
1213 gboolean retval;
1214 GError *rename_error = NULL;
1216 g_return_val_if_fail (filename != NULL, FALSE);
1217 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1218 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1219 g_return_val_if_fail (length >= -1, FALSE);
1221 if (length == -1)
1222 length = strlen (contents);
1224 tmp_filename = write_to_temp_file (contents, length, filename, error);
1226 if (!tmp_filename)
1228 retval = FALSE;
1229 goto out;
1232 if (!rename_file (tmp_filename, filename, &rename_error))
1234 #ifndef G_OS_WIN32
1236 g_unlink (tmp_filename);
1237 g_propagate_error (error, rename_error);
1238 retval = FALSE;
1239 goto out;
1241 #else /* G_OS_WIN32 */
1243 /* Renaming failed, but on Windows this may just mean
1244 * the file already exists. So if the target file
1245 * exists, try deleting it and do the rename again.
1247 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1249 g_unlink (tmp_filename);
1250 g_propagate_error (error, rename_error);
1251 retval = FALSE;
1252 goto out;
1255 g_error_free (rename_error);
1257 if (g_unlink (filename) == -1)
1259 int saved_errno = errno;
1260 set_file_error (error,
1261 filename,
1262 _("Existing file “%s” could not be removed: g_unlink() failed: %s"),
1263 saved_errno);
1264 g_unlink (tmp_filename);
1265 retval = FALSE;
1266 goto out;
1269 if (!rename_file (tmp_filename, filename, error))
1271 g_unlink (tmp_filename);
1272 retval = FALSE;
1273 goto out;
1276 #endif
1279 retval = TRUE;
1281 out:
1282 g_free (tmp_filename);
1283 return retval;
1287 * get_tmp_file based on the mkstemp implementation from the GNU C library.
1288 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1290 typedef gint (*GTmpFileCallback) (const gchar *, gint, gint);
1292 static gint
1293 get_tmp_file (gchar *tmpl,
1294 GTmpFileCallback f,
1295 int flags,
1296 int mode)
1298 char *XXXXXX;
1299 int count, fd;
1300 static const char letters[] =
1301 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1302 static const int NLETTERS = sizeof (letters) - 1;
1303 glong value;
1304 GTimeVal tv;
1305 static int counter = 0;
1307 g_return_val_if_fail (tmpl != NULL, -1);
1309 /* find the last occurrence of "XXXXXX" */
1310 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1312 if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1314 errno = EINVAL;
1315 return -1;
1318 /* Get some more or less random data. */
1319 g_get_current_time (&tv);
1320 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1322 for (count = 0; count < 100; value += 7777, ++count)
1324 glong v = value;
1326 /* Fill in the random bits. */
1327 XXXXXX[0] = letters[v % NLETTERS];
1328 v /= NLETTERS;
1329 XXXXXX[1] = letters[v % NLETTERS];
1330 v /= NLETTERS;
1331 XXXXXX[2] = letters[v % NLETTERS];
1332 v /= NLETTERS;
1333 XXXXXX[3] = letters[v % NLETTERS];
1334 v /= NLETTERS;
1335 XXXXXX[4] = letters[v % NLETTERS];
1336 v /= NLETTERS;
1337 XXXXXX[5] = letters[v % NLETTERS];
1339 fd = f (tmpl, flags, mode);
1341 if (fd >= 0)
1342 return fd;
1343 else if (errno != EEXIST)
1344 /* Any other error will apply also to other names we might
1345 * try, and there are 2^32 or so of them, so give up now.
1347 return -1;
1350 /* We got out of the loop because we ran out of combinations to try. */
1351 errno = EEXIST;
1352 return -1;
1355 /* Some GTmpFileCallback implementations.
1357 * Note: we cannot use open() or g_open() directly because even though
1358 * they appear compatible, they may be vararg functions and calling
1359 * varargs functions through a non-varargs type is undefined.
1361 static gint
1362 wrap_g_mkdir (const gchar *filename,
1363 int flags G_GNUC_UNUSED,
1364 int mode)
1366 /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1367 return g_mkdir (filename, mode);
1370 static gint
1371 wrap_g_open (const gchar *filename,
1372 int flags,
1373 int mode)
1375 return g_open (filename, flags, mode);
1379 * g_mkdtemp_full: (skip)
1380 * @tmpl: (type filename): template directory name
1381 * @mode: permissions to create the temporary directory with
1383 * Creates a temporary directory. See the mkdtemp() documentation
1384 * on most UNIX-like systems.
1386 * The parameter is a string that should follow the rules for
1387 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1388 * g_mkdtemp_full() is slightly more flexible than mkdtemp() in that the
1389 * sequence does not have to occur at the very end of the template
1390 * and you can pass a @mode. The X string will be modified to form
1391 * the name of a directory that didn't exist. The string should be
1392 * in the GLib file name encoding. Most importantly, on Windows it
1393 * should be in UTF-8.
1395 * If you are going to be creating a temporary directory inside the
1396 * directory returned by g_get_tmp_dir(), you might want to use
1397 * g_dir_make_tmp() instead.
1399 * Returns: (nullable) (type filename): A pointer to @tmpl, which has been
1400 * modified to hold the directory name. In case of errors, %NULL is
1401 * returned, and %errno will be set.
1403 * Since: 2.30
1405 gchar *
1406 g_mkdtemp_full (gchar *tmpl,
1407 gint mode)
1409 if (get_tmp_file (tmpl, wrap_g_mkdir, 0, mode) == -1)
1410 return NULL;
1411 else
1412 return tmpl;
1416 * g_mkdtemp: (skip)
1417 * @tmpl: (type filename): template directory name
1419 * Creates a temporary directory. See the mkdtemp() documentation
1420 * on most UNIX-like systems.
1422 * The parameter is a string that should follow the rules for
1423 * mkdtemp() templates, i.e. contain the string "XXXXXX".
1424 * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1425 * sequence does not have to occur at the very end of the template.
1426 * The X string will be modified to form the name of a directory that
1427 * didn't exist.
1428 * The string should be in the GLib file name encoding. Most importantly,
1429 * on Windows it should be in UTF-8.
1431 * If you are going to be creating a temporary directory inside the
1432 * directory returned by g_get_tmp_dir(), you might want to use
1433 * g_dir_make_tmp() instead.
1435 * Returns: (nullable) (type filename): A pointer to @tmpl, which has been
1436 * modified to hold the directory name. In case of errors, %NULL is
1437 * returned and %errno will be set.
1439 * Since: 2.30
1441 gchar *
1442 g_mkdtemp (gchar *tmpl)
1444 return g_mkdtemp_full (tmpl, 0700);
1448 * g_mkstemp_full: (skip)
1449 * @tmpl: (type filename): template filename
1450 * @flags: flags to pass to an open() call in addition to O_EXCL
1451 * and O_CREAT, which are passed automatically
1452 * @mode: permissions to create the temporary file with
1454 * Opens a temporary file. See the mkstemp() documentation
1455 * on most UNIX-like systems.
1457 * The parameter is a string that should follow the rules for
1458 * mkstemp() templates, i.e. contain the string "XXXXXX".
1459 * g_mkstemp_full() is slightly more flexible than mkstemp()
1460 * in that the sequence does not have to occur at the very end of the
1461 * template and you can pass a @mode and additional @flags. The X
1462 * string will be modified to form the name of a file that didn't exist.
1463 * The string should be in the GLib file name encoding. Most importantly,
1464 * on Windows it should be in UTF-8.
1466 * Returns: A file handle (as from open()) to the file
1467 * opened for reading and writing. The file handle should be
1468 * closed with close(). In case of errors, -1 is returned
1469 * and %errno will be set.
1471 * Since: 2.22
1473 gint
1474 g_mkstemp_full (gchar *tmpl,
1475 gint flags,
1476 gint mode)
1478 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1479 return get_tmp_file (tmpl, wrap_g_open,
1480 flags | O_CREAT | O_EXCL, mode);
1484 * g_mkstemp: (skip)
1485 * @tmpl: (type filename): template filename
1487 * Opens a temporary file. See the mkstemp() documentation
1488 * on most UNIX-like systems.
1490 * The parameter is a string that should follow the rules for
1491 * mkstemp() templates, i.e. contain the string "XXXXXX".
1492 * g_mkstemp() is slightly more flexible than mkstemp() in that the
1493 * sequence does not have to occur at the very end of the template.
1494 * The X string will be modified to form the name of a file that
1495 * didn't exist. The string should be in the GLib file name encoding.
1496 * Most importantly, on Windows it should be in UTF-8.
1498 * Returns: A file handle (as from open()) to the file
1499 * opened for reading and writing. The file is opened in binary
1500 * mode on platforms where there is a difference. The file handle
1501 * should be closed with close(). In case of errors, -1 is
1502 * returned and %errno will be set.
1504 gint
1505 g_mkstemp (gchar *tmpl)
1507 return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1510 static gint
1511 g_get_tmp_name (const gchar *tmpl,
1512 gchar **name_used,
1513 GTmpFileCallback f,
1514 gint flags,
1515 gint mode,
1516 GError **error)
1518 int retval;
1519 const char *tmpdir;
1520 const char *sep;
1521 char *fulltemplate;
1522 const char *slash;
1524 if (tmpl == NULL)
1525 tmpl = ".XXXXXX";
1527 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1528 #ifdef G_OS_WIN32
1529 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1530 #endif
1533 gchar *display_tmpl = g_filename_display_name (tmpl);
1534 char c[2];
1535 c[0] = *slash;
1536 c[1] = '\0';
1538 g_set_error (error,
1539 G_FILE_ERROR,
1540 G_FILE_ERROR_FAILED,
1541 _("Template “%s” invalid, should not contain a “%s”"),
1542 display_tmpl, c);
1543 g_free (display_tmpl);
1545 return -1;
1548 if (strstr (tmpl, "XXXXXX") == NULL)
1550 gchar *display_tmpl = g_filename_display_name (tmpl);
1551 g_set_error (error,
1552 G_FILE_ERROR,
1553 G_FILE_ERROR_FAILED,
1554 _("Template “%s” doesn’t contain XXXXXX"),
1555 display_tmpl);
1556 g_free (display_tmpl);
1557 return -1;
1560 tmpdir = g_get_tmp_dir ();
1562 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1563 sep = "";
1564 else
1565 sep = G_DIR_SEPARATOR_S;
1567 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1569 retval = get_tmp_file (fulltemplate, f, flags, mode);
1570 if (retval == -1)
1572 int saved_errno = errno;
1573 set_file_error (error,
1574 fulltemplate,
1575 _("Failed to create file “%s”: %s"),
1576 saved_errno);
1577 g_free (fulltemplate);
1578 return -1;
1581 *name_used = fulltemplate;
1583 return retval;
1587 * g_file_open_tmp:
1588 * @tmpl: (type filename) (nullable): Template for file name, as in
1589 * g_mkstemp(), basename only, or %NULL for a default template
1590 * @name_used: (out) (type filename): location to store actual name used,
1591 * or %NULL
1592 * @error: return location for a #GError
1594 * Opens a file for writing in the preferred directory for temporary
1595 * files (as returned by g_get_tmp_dir()).
1597 * @tmpl should be a string in the GLib file name encoding containing
1598 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1599 * However, unlike these functions, the template should only be a
1600 * basename, no directory components are allowed. If template is
1601 * %NULL, a default template is used.
1603 * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
1604 * modified, and might thus be a read-only literal string.
1606 * Upon success, and if @name_used is non-%NULL, the actual name used
1607 * is returned in @name_used. This string should be freed with g_free()
1608 * when not needed any longer. The returned name is in the GLib file
1609 * name encoding.
1611 * Returns: A file handle (as from open()) to the file opened for
1612 * reading and writing. The file is opened in binary mode on platforms
1613 * where there is a difference. The file handle should be closed with
1614 * close(). In case of errors, -1 is returned and @error will be set.
1616 gint
1617 g_file_open_tmp (const gchar *tmpl,
1618 gchar **name_used,
1619 GError **error)
1621 gchar *fulltemplate;
1622 gint result;
1624 g_return_val_if_fail (error == NULL || *error == NULL, -1);
1626 result = g_get_tmp_name (tmpl, &fulltemplate,
1627 wrap_g_open,
1628 O_CREAT | O_EXCL | O_RDWR | O_BINARY,
1629 0600,
1630 error);
1631 if (result != -1)
1633 if (name_used)
1634 *name_used = fulltemplate;
1635 else
1636 g_free (fulltemplate);
1639 return result;
1643 * g_dir_make_tmp:
1644 * @tmpl: (type filename) (nullable): Template for directory name,
1645 * as in g_mkdtemp(), basename only, or %NULL for a default template
1646 * @error: return location for a #GError
1648 * Creates a subdirectory in the preferred directory for temporary
1649 * files (as returned by g_get_tmp_dir()).
1651 * @tmpl should be a string in the GLib file name encoding containing
1652 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1653 * However, unlike these functions, the template should only be a
1654 * basename, no directory components are allowed. If template is
1655 * %NULL, a default template is used.
1657 * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
1658 * modified, and might thus be a read-only literal string.
1660 * Returns: (type filename): The actual name used. This string
1661 * should be freed with g_free() when not needed any longer and is
1662 * is in the GLib file name encoding. In case of errors, %NULL is
1663 * returned and @error will be set.
1665 * Since: 2.30
1667 gchar *
1668 g_dir_make_tmp (const gchar *tmpl,
1669 GError **error)
1671 gchar *fulltemplate;
1673 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1675 if (g_get_tmp_name (tmpl, &fulltemplate, wrap_g_mkdir, 0, 0700, error) == -1)
1676 return NULL;
1677 else
1678 return fulltemplate;
1681 static gchar *
1682 g_build_path_va (const gchar *separator,
1683 const gchar *first_element,
1684 va_list *args,
1685 gchar **str_array)
1687 GString *result;
1688 gint separator_len = strlen (separator);
1689 gboolean is_first = TRUE;
1690 gboolean have_leading = FALSE;
1691 const gchar *single_element = NULL;
1692 const gchar *next_element;
1693 const gchar *last_trailing = NULL;
1694 gint i = 0;
1696 result = g_string_new (NULL);
1698 if (str_array)
1699 next_element = str_array[i++];
1700 else
1701 next_element = first_element;
1703 while (TRUE)
1705 const gchar *element;
1706 const gchar *start;
1707 const gchar *end;
1709 if (next_element)
1711 element = next_element;
1712 if (str_array)
1713 next_element = str_array[i++];
1714 else
1715 next_element = va_arg (*args, gchar *);
1717 else
1718 break;
1720 /* Ignore empty elements */
1721 if (!*element)
1722 continue;
1724 start = element;
1726 if (separator_len)
1728 while (strncmp (start, separator, separator_len) == 0)
1729 start += separator_len;
1732 end = start + strlen (start);
1734 if (separator_len)
1736 while (end >= start + separator_len &&
1737 strncmp (end - separator_len, separator, separator_len) == 0)
1738 end -= separator_len;
1740 last_trailing = end;
1741 while (last_trailing >= element + separator_len &&
1742 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1743 last_trailing -= separator_len;
1745 if (!have_leading)
1747 /* If the leading and trailing separator strings are in the
1748 * same element and overlap, the result is exactly that element
1750 if (last_trailing <= start)
1751 single_element = element;
1753 g_string_append_len (result, element, start - element);
1754 have_leading = TRUE;
1756 else
1757 single_element = NULL;
1760 if (end == start)
1761 continue;
1763 if (!is_first)
1764 g_string_append (result, separator);
1766 g_string_append_len (result, start, end - start);
1767 is_first = FALSE;
1770 if (single_element)
1772 g_string_free (result, TRUE);
1773 return g_strdup (single_element);
1775 else
1777 if (last_trailing)
1778 g_string_append (result, last_trailing);
1780 return g_string_free (result, FALSE);
1785 * g_build_pathv:
1786 * @separator: a string used to separator the elements of the path.
1787 * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
1788 * array of strings containing the path elements.
1790 * Behaves exactly like g_build_path(), but takes the path elements
1791 * as a string array, instead of varargs. This function is mainly
1792 * meant for language bindings.
1794 * Returns: (type filename): a newly-allocated string that must be freed
1795 * with g_free().
1797 * Since: 2.8
1799 gchar *
1800 g_build_pathv (const gchar *separator,
1801 gchar **args)
1803 if (!args)
1804 return NULL;
1806 return g_build_path_va (separator, NULL, NULL, args);
1811 * g_build_path:
1812 * @separator: (type filename): a string used to separator the elements of the path.
1813 * @first_element: (type filename): the first element in the path
1814 * @...: remaining elements in path, terminated by %NULL
1816 * Creates a path from a series of elements using @separator as the
1817 * separator between elements. At the boundary between two elements,
1818 * any trailing occurrences of separator in the first element, or
1819 * leading occurrences of separator in the second element are removed
1820 * and exactly one copy of the separator is inserted.
1822 * Empty elements are ignored.
1824 * The number of leading copies of the separator on the result is
1825 * the same as the number of leading copies of the separator on
1826 * the first non-empty element.
1828 * The number of trailing copies of the separator on the result is
1829 * the same as the number of trailing copies of the separator on
1830 * the last non-empty element. (Determination of the number of
1831 * trailing copies is done without stripping leading copies, so
1832 * if the separator is `ABA`, then `ABABA` has 1 trailing copy.)
1834 * However, if there is only a single non-empty element, and there
1835 * are no characters in that element not part of the leading or
1836 * trailing separators, then the result is exactly the original value
1837 * of that element.
1839 * Other than for determination of the number of leading and trailing
1840 * copies of the separator, elements consisting only of copies
1841 * of the separator are ignored.
1843 * Returns: (type filename): a newly-allocated string that must be freed with
1844 * g_free().
1846 gchar *
1847 g_build_path (const gchar *separator,
1848 const gchar *first_element,
1849 ...)
1851 gchar *str;
1852 va_list args;
1854 g_return_val_if_fail (separator != NULL, NULL);
1856 va_start (args, first_element);
1857 str = g_build_path_va (separator, first_element, &args, NULL);
1858 va_end (args);
1860 return str;
1863 #ifdef G_OS_WIN32
1865 static gchar *
1866 g_build_pathname_va (const gchar *first_element,
1867 va_list *args,
1868 gchar **str_array)
1870 /* Code copied from g_build_pathv(), and modified to use two
1871 * alternative single-character separators.
1873 GString *result;
1874 gboolean is_first = TRUE;
1875 gboolean have_leading = FALSE;
1876 const gchar *single_element = NULL;
1877 const gchar *next_element;
1878 const gchar *last_trailing = NULL;
1879 gchar current_separator = '\\';
1880 gint i = 0;
1882 result = g_string_new (NULL);
1884 if (str_array)
1885 next_element = str_array[i++];
1886 else
1887 next_element = first_element;
1889 while (TRUE)
1891 const gchar *element;
1892 const gchar *start;
1893 const gchar *end;
1895 if (next_element)
1897 element = next_element;
1898 if (str_array)
1899 next_element = str_array[i++];
1900 else
1901 next_element = va_arg (*args, gchar *);
1903 else
1904 break;
1906 /* Ignore empty elements */
1907 if (!*element)
1908 continue;
1910 start = element;
1912 if (TRUE)
1914 while (start &&
1915 (*start == '\\' || *start == '/'))
1917 current_separator = *start;
1918 start++;
1922 end = start + strlen (start);
1924 if (TRUE)
1926 while (end >= start + 1 &&
1927 (end[-1] == '\\' || end[-1] == '/'))
1929 current_separator = end[-1];
1930 end--;
1933 last_trailing = end;
1934 while (last_trailing >= element + 1 &&
1935 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1936 last_trailing--;
1938 if (!have_leading)
1940 /* If the leading and trailing separator strings are in the
1941 * same element and overlap, the result is exactly that element
1943 if (last_trailing <= start)
1944 single_element = element;
1946 g_string_append_len (result, element, start - element);
1947 have_leading = TRUE;
1949 else
1950 single_element = NULL;
1953 if (end == start)
1954 continue;
1956 if (!is_first)
1957 g_string_append_len (result, &current_separator, 1);
1959 g_string_append_len (result, start, end - start);
1960 is_first = FALSE;
1963 if (single_element)
1965 g_string_free (result, TRUE);
1966 return g_strdup (single_element);
1968 else
1970 if (last_trailing)
1971 g_string_append (result, last_trailing);
1973 return g_string_free (result, FALSE);
1977 #endif
1979 static gchar *
1980 g_build_filename_va (const gchar *first_argument,
1981 va_list *args,
1982 gchar **str_array)
1984 gchar *str;
1986 #ifndef G_OS_WIN32
1987 str = g_build_path_va (G_DIR_SEPARATOR_S, first_argument, args, str_array);
1988 #else
1989 str = g_build_pathname_va (first_argument, args, str_array);
1990 #endif
1992 return str;
1996 * g_build_filename_valist:
1997 * @first_element: (type filename): the first element in the path
1998 * @args: va_list of remaining elements in path
2000 * Behaves exactly like g_build_filename(), but takes the path elements
2001 * as a va_list. This function is mainly meant for language bindings.
2003 * Returns: (type filename): a newly-allocated string that must be freed
2004 * with g_free().
2006 * Since: 2.56
2008 gchar *
2009 g_build_filename_valist (const gchar *first_element,
2010 va_list *args)
2012 g_return_val_if_fail (first_element != NULL, NULL);
2014 return g_build_filename_va (first_element, args, NULL);
2018 * g_build_filenamev:
2019 * @args: (array zero-terminated=1) (element-type filename): %NULL-terminated
2020 * array of strings containing the path elements.
2022 * Behaves exactly like g_build_filename(), but takes the path elements
2023 * as a string array, instead of varargs. This function is mainly
2024 * meant for language bindings.
2026 * Returns: (type filename): a newly-allocated string that must be freed
2027 * with g_free().
2029 * Since: 2.8
2031 gchar *
2032 g_build_filenamev (gchar **args)
2034 return g_build_filename_va (NULL, NULL, args);
2038 * g_build_filename:
2039 * @first_element: (type filename): the first element in the path
2040 * @...: remaining elements in path, terminated by %NULL
2042 * Creates a filename from a series of elements using the correct
2043 * separator for filenames.
2045 * On Unix, this function behaves identically to `g_build_path
2046 * (G_DIR_SEPARATOR_S, first_element, ....)`.
2048 * On Windows, it takes into account that either the backslash
2049 * (`\` or slash (`/`) can be used as separator in filenames, but
2050 * otherwise behaves as on UNIX. When file pathname separators need
2051 * to be inserted, the one that last previously occurred in the
2052 * parameters (reading from left to right) is used.
2054 * No attempt is made to force the resulting filename to be an absolute
2055 * path. If the first element is a relative path, the result will
2056 * be a relative path.
2058 * Returns: (type filename): a newly-allocated string that must be freed with
2059 * g_free().
2061 gchar *
2062 g_build_filename (const gchar *first_element,
2063 ...)
2065 gchar *str;
2066 va_list args;
2068 va_start (args, first_element);
2069 str = g_build_filename_va (first_element, &args, NULL);
2070 va_end (args);
2072 return str;
2076 * g_file_read_link:
2077 * @filename: (type filename): the symbolic link
2078 * @error: return location for a #GError
2080 * Reads the contents of the symbolic link @filename like the POSIX
2081 * readlink() function. The returned string is in the encoding used
2082 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
2084 * Returns: (type filename): A newly-allocated string with the contents of
2085 * the symbolic link, or %NULL if an error occurred.
2087 * Since: 2.4
2089 gchar *
2090 g_file_read_link (const gchar *filename,
2091 GError **error)
2093 #if defined (HAVE_READLINK) || defined (G_OS_WIN32)
2094 gchar *buffer;
2095 size_t size;
2096 gssize read_size;
2098 g_return_val_if_fail (filename != NULL, NULL);
2099 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2101 size = 256;
2102 buffer = g_malloc (size);
2104 while (TRUE)
2106 #ifndef G_OS_WIN32
2107 read_size = readlink (filename, buffer, size);
2108 #else
2109 read_size = g_win32_readlink_utf8 (filename, buffer, size);
2110 #endif
2111 if (read_size < 0)
2113 int saved_errno = errno;
2114 set_file_error (error,
2115 filename,
2116 _("Failed to read the symbolic link “%s”: %s"),
2117 saved_errno);
2118 g_free (buffer);
2119 return NULL;
2122 if ((size_t) read_size < size)
2124 buffer[read_size] = 0;
2125 return buffer;
2128 size *= 2;
2129 buffer = g_realloc (buffer, size);
2131 #else
2132 g_return_val_if_fail (filename != NULL, NULL);
2133 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2135 g_set_error_literal (error,
2136 G_FILE_ERROR,
2137 G_FILE_ERROR_INVAL,
2138 _("Symbolic links not supported"));
2140 return NULL;
2141 #endif
2145 * g_path_is_absolute:
2146 * @file_name: (type filename): a file name
2148 * Returns %TRUE if the given @file_name is an absolute file name.
2149 * Note that this is a somewhat vague concept on Windows.
2151 * On POSIX systems, an absolute file name is well-defined. It always
2152 * starts from the single root directory. For example "/usr/local".
2154 * On Windows, the concepts of current drive and drive-specific
2155 * current directory introduce vagueness. This function interprets as
2156 * an absolute file name one that either begins with a directory
2157 * separator such as "\Users\tml" or begins with the root on a drive,
2158 * for example "C:\Windows". The first case also includes UNC paths
2159 * such as "\\\\myserver\docs\foo". In all cases, either slashes or
2160 * backslashes are accepted.
2162 * Note that a file name relative to the current drive root does not
2163 * truly specify a file uniquely over time and across processes, as
2164 * the current drive is a per-process value and can be changed.
2166 * File names relative the current directory on some specific drive,
2167 * such as "D:foo/bar", are not interpreted as absolute by this
2168 * function, but they obviously are not relative to the normal current
2169 * directory as returned by getcwd() or g_get_current_dir()
2170 * either. Such paths should be avoided, or need to be handled using
2171 * Windows-specific code.
2173 * Returns: %TRUE if @file_name is absolute
2175 gboolean
2176 g_path_is_absolute (const gchar *file_name)
2178 g_return_val_if_fail (file_name != NULL, FALSE);
2180 if (G_IS_DIR_SEPARATOR (file_name[0]))
2181 return TRUE;
2183 #ifdef G_OS_WIN32
2184 /* Recognize drive letter on native Windows */
2185 if (g_ascii_isalpha (file_name[0]) &&
2186 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
2187 return TRUE;
2188 #endif
2190 return FALSE;
2194 * g_path_skip_root:
2195 * @file_name: (type filename): a file name
2197 * Returns a pointer into @file_name after the root component,
2198 * i.e. after the "/" in UNIX or "C:\" under Windows. If @file_name
2199 * is not an absolute path it returns %NULL.
2201 * Returns: (type filename) (nullable): a pointer into @file_name after the
2202 * root component
2204 const gchar *
2205 g_path_skip_root (const gchar *file_name)
2207 g_return_val_if_fail (file_name != NULL, NULL);
2209 #ifdef G_PLATFORM_WIN32
2210 /* Skip \\server\share or //server/share */
2211 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2212 G_IS_DIR_SEPARATOR (file_name[1]) &&
2213 file_name[2] &&
2214 !G_IS_DIR_SEPARATOR (file_name[2]))
2216 gchar *p;
2217 p = strchr (file_name + 2, G_DIR_SEPARATOR);
2219 #ifdef G_OS_WIN32
2221 gchar *q;
2223 q = strchr (file_name + 2, '/');
2224 if (p == NULL || (q != NULL && q < p))
2225 p = q;
2227 #endif
2229 if (p && p > file_name + 2 && p[1])
2231 file_name = p + 1;
2233 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
2234 file_name++;
2236 /* Possibly skip a backslash after the share name */
2237 if (G_IS_DIR_SEPARATOR (file_name[0]))
2238 file_name++;
2240 return (gchar *)file_name;
2243 #endif
2245 /* Skip initial slashes */
2246 if (G_IS_DIR_SEPARATOR (file_name[0]))
2248 while (G_IS_DIR_SEPARATOR (file_name[0]))
2249 file_name++;
2250 return (gchar *)file_name;
2253 #ifdef G_OS_WIN32
2254 /* Skip X:\ */
2255 if (g_ascii_isalpha (file_name[0]) &&
2256 file_name[1] == ':' &&
2257 G_IS_DIR_SEPARATOR (file_name[2]))
2258 return (gchar *)file_name + 3;
2259 #endif
2261 return NULL;
2265 * g_basename:
2266 * @file_name: (type filename): the name of the file
2268 * Gets the name of the file without any leading directory
2269 * components. It returns a pointer into the given file name
2270 * string.
2272 * Returns: (type filename): the name of the file without any leading
2273 * directory components
2275 * Deprecated:2.2: Use g_path_get_basename() instead, but notice
2276 * that g_path_get_basename() allocates new memory for the
2277 * returned string, unlike this function which returns a pointer
2278 * into the argument.
2280 const gchar *
2281 g_basename (const gchar *file_name)
2283 gchar *base;
2285 g_return_val_if_fail (file_name != NULL, NULL);
2287 base = strrchr (file_name, G_DIR_SEPARATOR);
2289 #ifdef G_OS_WIN32
2291 gchar *q;
2292 q = strrchr (file_name, '/');
2293 if (base == NULL || (q != NULL && q > base))
2294 base = q;
2296 #endif
2298 if (base)
2299 return base + 1;
2301 #ifdef G_OS_WIN32
2302 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2303 return (gchar*) file_name + 2;
2304 #endif
2306 return (gchar*) file_name;
2310 * g_path_get_basename:
2311 * @file_name: (type filename): the name of the file
2313 * Gets the last component of the filename.
2315 * If @file_name ends with a directory separator it gets the component
2316 * before the last slash. If @file_name consists only of directory
2317 * separators (and on Windows, possibly a drive letter), a single
2318 * separator is returned. If @file_name is empty, it gets ".".
2320 * Returns: (type filename): a newly allocated string containing the last
2321 * component of the filename
2323 gchar *
2324 g_path_get_basename (const gchar *file_name)
2326 gssize base;
2327 gssize last_nonslash;
2328 gsize len;
2329 gchar *retval;
2331 g_return_val_if_fail (file_name != NULL, NULL);
2333 if (file_name[0] == '\0')
2334 return g_strdup (".");
2336 last_nonslash = strlen (file_name) - 1;
2338 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
2339 last_nonslash--;
2341 if (last_nonslash == -1)
2342 /* string only containing slashes */
2343 return g_strdup (G_DIR_SEPARATOR_S);
2345 #ifdef G_OS_WIN32
2346 if (last_nonslash == 1 &&
2347 g_ascii_isalpha (file_name[0]) &&
2348 file_name[1] == ':')
2349 /* string only containing slashes and a drive */
2350 return g_strdup (G_DIR_SEPARATOR_S);
2351 #endif
2352 base = last_nonslash;
2354 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
2355 base--;
2357 #ifdef G_OS_WIN32
2358 if (base == -1 &&
2359 g_ascii_isalpha (file_name[0]) &&
2360 file_name[1] == ':')
2361 base = 1;
2362 #endif /* G_OS_WIN32 */
2364 len = last_nonslash - base;
2365 retval = g_malloc (len + 1);
2366 memcpy (retval, file_name + base + 1, len);
2367 retval [len] = '\0';
2369 return retval;
2373 * g_dirname:
2374 * @file_name: (type filename): the name of the file
2376 * Gets the directory components of a file name.
2378 * If the file name has no directory components "." is returned.
2379 * The returned string should be freed when no longer needed.
2381 * Returns: (type filename): the directory components of the file
2383 * Deprecated: use g_path_get_dirname() instead
2387 * g_path_get_dirname:
2388 * @file_name: (type filename): the name of the file
2390 * Gets the directory components of a file name.
2392 * If the file name has no directory components "." is returned.
2393 * The returned string should be freed when no longer needed.
2395 * Returns: (type filename): the directory components of the file
2397 gchar *
2398 g_path_get_dirname (const gchar *file_name)
2400 gchar *base;
2401 gsize len;
2403 g_return_val_if_fail (file_name != NULL, NULL);
2405 base = strrchr (file_name, G_DIR_SEPARATOR);
2407 #ifdef G_OS_WIN32
2409 gchar *q;
2410 q = strrchr (file_name, '/');
2411 if (base == NULL || (q != NULL && q > base))
2412 base = q;
2414 #endif
2416 if (!base)
2418 #ifdef G_OS_WIN32
2419 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2421 gchar drive_colon_dot[4];
2423 drive_colon_dot[0] = file_name[0];
2424 drive_colon_dot[1] = ':';
2425 drive_colon_dot[2] = '.';
2426 drive_colon_dot[3] = '\0';
2428 return g_strdup (drive_colon_dot);
2430 #endif
2431 return g_strdup (".");
2434 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
2435 base--;
2437 #ifdef G_OS_WIN32
2438 /* base points to the char before the last slash.
2440 * In case file_name is the root of a drive (X:\) or a child of the
2441 * root of a drive (X:\foo), include the slash.
2443 * In case file_name is the root share of an UNC path
2444 * (\\server\share), add a slash, returning \\server\share\ .
2446 * In case file_name is a direct child of a share in an UNC path
2447 * (\\server\share\foo), include the slash after the share name,
2448 * returning \\server\share\ .
2450 if (base == file_name + 1 &&
2451 g_ascii_isalpha (file_name[0]) &&
2452 file_name[1] == ':')
2453 base++;
2454 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2455 G_IS_DIR_SEPARATOR (file_name[1]) &&
2456 file_name[2] &&
2457 !G_IS_DIR_SEPARATOR (file_name[2]) &&
2458 base >= file_name + 2)
2460 const gchar *p = file_name + 2;
2461 while (*p && !G_IS_DIR_SEPARATOR (*p))
2462 p++;
2463 if (p == base + 1)
2465 len = (guint) strlen (file_name) + 1;
2466 base = g_new (gchar, len + 1);
2467 strcpy (base, file_name);
2468 base[len-1] = G_DIR_SEPARATOR;
2469 base[len] = 0;
2470 return base;
2472 if (G_IS_DIR_SEPARATOR (*p))
2474 p++;
2475 while (*p && !G_IS_DIR_SEPARATOR (*p))
2476 p++;
2477 if (p == base + 1)
2478 base++;
2481 #endif
2483 len = (guint) 1 + base - file_name;
2484 base = g_new (gchar, len + 1);
2485 memmove (base, file_name, len);
2486 base[len] = 0;
2488 return base;
2492 * g_canonicalize_filename:
2493 * @filename: (type filename): the name of the file
2494 * @relative_to: (type filename) (nullable): the relative directory, or %NULL
2495 * to use the current working directory
2497 * Gets the canonical file name from @filename. All triple slashes are turned into
2498 * single slashes, and all `..` and `.`s resolved against @relative_to.
2500 * Symlinks are not followed, and the returned path is guaranteed to be absolute.
2502 * If @filename is an absolute path, @relative_to is ignored. Otherwise,
2503 * @relative_to will be prepended to @filename to make it absolute. @relative_to
2504 * must be an absolute path, or %NULL. If @relative_to is %NULL, it'll fallback
2505 * to g_get_current_dir().
2507 * This function never fails, and will canonicalize file paths even if they don't
2508 * exist.
2510 * No file system I/O is done.
2512 * Returns: (type filename) (transfer full): a newly allocated string with the
2513 * canonical file path
2514 * Since: 2.58
2516 gchar *
2517 g_canonicalize_filename (const gchar *filename,
2518 const gchar *relative_to)
2520 gchar *canon, *start, *p, *q;
2521 guint i;
2523 g_return_val_if_fail (relative_to == NULL || g_path_is_absolute (relative_to), NULL);
2525 if (!g_path_is_absolute (filename))
2527 gchar *cwd_allocated = NULL;
2528 const gchar *cwd;
2530 if (relative_to != NULL)
2531 cwd = relative_to;
2532 else
2533 cwd = cwd_allocated = g_get_current_dir ();
2535 canon = g_build_filename (cwd, filename, NULL);
2536 g_free (cwd_allocated);
2538 else
2540 canon = g_strdup (filename);
2543 start = (char *)g_path_skip_root (canon);
2545 if (start == NULL)
2547 /* This shouldn't really happen, as g_get_current_dir() should
2548 return an absolute pathname, but bug 573843 shows this is
2549 not always happening */
2550 g_free (canon);
2551 return g_build_filename (G_DIR_SEPARATOR_S, filename, NULL);
2554 /* POSIX allows double slashes at the start to
2555 * mean something special (as does windows too).
2556 * So, "//" != "/", but more than two slashes
2557 * is treated as "/".
2559 i = 0;
2560 for (p = start - 1;
2561 (p >= canon) &&
2562 G_IS_DIR_SEPARATOR (*p);
2563 p--)
2564 i++;
2565 if (i > 2)
2567 i -= 1;
2568 start -= i;
2569 memmove (start, start+i, strlen (start+i) + 1);
2572 /* Make sure we're using the canonical dir separator */
2573 p++;
2574 while (p < start && G_IS_DIR_SEPARATOR (*p))
2575 *p++ = G_DIR_SEPARATOR;
2577 p = start;
2578 while (*p != 0)
2580 if (p[0] == '.' && (p[1] == 0 || G_IS_DIR_SEPARATOR (p[1])))
2582 memmove (p, p+1, strlen (p+1)+1);
2584 else if (p[0] == '.' && p[1] == '.' && (p[2] == 0 || G_IS_DIR_SEPARATOR (p[2])))
2586 q = p + 2;
2587 /* Skip previous separator */
2588 p = p - 2;
2589 if (p < start)
2590 p = start;
2591 while (p > start && !G_IS_DIR_SEPARATOR (*p))
2592 p--;
2593 if (G_IS_DIR_SEPARATOR (*p))
2594 *p++ = G_DIR_SEPARATOR;
2595 memmove (p, q, strlen (q)+1);
2597 else
2599 /* Skip until next separator */
2600 while (*p != 0 && !G_IS_DIR_SEPARATOR (*p))
2601 p++;
2603 if (*p != 0)
2605 /* Canonicalize one separator */
2606 *p++ = G_DIR_SEPARATOR;
2610 /* Remove additional separators */
2611 q = p;
2612 while (*q && G_IS_DIR_SEPARATOR (*q))
2613 q++;
2615 if (p != q)
2616 memmove (p, q, strlen (q) + 1);
2619 /* Remove trailing slashes */
2620 if (p > start && G_IS_DIR_SEPARATOR (*(p-1)))
2621 *(p-1) = 0;
2623 return canon;
2626 #if defined(MAXPATHLEN)
2627 #define G_PATH_LENGTH MAXPATHLEN
2628 #elif defined(PATH_MAX)
2629 #define G_PATH_LENGTH PATH_MAX
2630 #elif defined(_PC_PATH_MAX)
2631 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
2632 #else
2633 #define G_PATH_LENGTH 2048
2634 #endif
2637 * g_get_current_dir:
2639 * Gets the current directory.
2641 * The returned string should be freed when no longer needed.
2642 * The encoding of the returned string is system defined.
2643 * On Windows, it is always UTF-8.
2645 * Since GLib 2.40, this function will return the value of the "PWD"
2646 * environment variable if it is set and it happens to be the same as
2647 * the current directory. This can make a difference in the case that
2648 * the current directory is the target of a symbolic link.
2650 * Returns: (type filename): the current directory
2652 gchar *
2653 g_get_current_dir (void)
2655 #ifdef G_OS_WIN32
2657 gchar *dir = NULL;
2658 wchar_t dummy[2], *wdir;
2659 int len;
2661 len = GetCurrentDirectoryW (2, dummy);
2662 wdir = g_new (wchar_t, len);
2664 if (GetCurrentDirectoryW (len, wdir) == len - 1)
2665 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
2667 g_free (wdir);
2669 if (dir == NULL)
2670 dir = g_strdup ("\\");
2672 return dir;
2674 #else
2675 const gchar *pwd;
2676 gchar *buffer = NULL;
2677 gchar *dir = NULL;
2678 static gulong max_len = 0;
2679 struct stat pwdbuf, dotbuf;
2681 pwd = g_getenv ("PWD");
2682 if (pwd != NULL &&
2683 g_stat (".", &dotbuf) == 0 && g_stat (pwd, &pwdbuf) == 0 &&
2684 dotbuf.st_dev == pwdbuf.st_dev && dotbuf.st_ino == pwdbuf.st_ino)
2685 return g_strdup (pwd);
2687 if (max_len == 0)
2688 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
2690 while (max_len < G_MAXULONG / 2)
2692 g_free (buffer);
2693 buffer = g_new (gchar, max_len + 1);
2694 *buffer = 0;
2695 dir = getcwd (buffer, max_len);
2697 if (dir || errno != ERANGE)
2698 break;
2700 max_len *= 2;
2703 if (!dir || !*buffer)
2705 /* hm, should we g_error() out here?
2706 * this can happen if e.g. "./" has mode \0000
2708 buffer[0] = G_DIR_SEPARATOR;
2709 buffer[1] = 0;
2712 dir = g_strdup (buffer);
2713 g_free (buffer);
2715 return dir;
2717 #endif /* !G_OS_WIN32 */
2720 #ifdef G_OS_WIN32
2722 /* Binary compatibility versions. Not for newly compiled code. */
2724 _GLIB_EXTERN gboolean g_file_test_utf8 (const gchar *filename,
2725 GFileTest test);
2726 _GLIB_EXTERN gboolean g_file_get_contents_utf8 (const gchar *filename,
2727 gchar **contents,
2728 gsize *length,
2729 GError **error);
2730 _GLIB_EXTERN gint g_mkstemp_utf8 (gchar *tmpl);
2731 _GLIB_EXTERN gint g_file_open_tmp_utf8 (const gchar *tmpl,
2732 gchar **name_used,
2733 GError **error);
2734 _GLIB_EXTERN gchar *g_get_current_dir_utf8 (void);
2737 gboolean
2738 g_file_test_utf8 (const gchar *filename,
2739 GFileTest test)
2741 return g_file_test (filename, test);
2744 gboolean
2745 g_file_get_contents_utf8 (const gchar *filename,
2746 gchar **contents,
2747 gsize *length,
2748 GError **error)
2750 return g_file_get_contents (filename, contents, length, error);
2753 gint
2754 g_mkstemp_utf8 (gchar *tmpl)
2756 return g_mkstemp (tmpl);
2759 gint
2760 g_file_open_tmp_utf8 (const gchar *tmpl,
2761 gchar **name_used,
2762 GError **error)
2764 return g_file_open_tmp (tmpl, name_used, error);
2767 gchar *
2768 g_get_current_dir_utf8 (void)
2770 return g_get_current_dir ();
2773 #endif