1 /* gfileutils.c - File utility functions
3 * Copyright 2000 Red Hat, Inc.
5 * GLib is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU Lesser General Public License as
7 * published by the Free Software Foundation; either version 2 of the
8 * License, or (at your option) any later version.
10 * GLib is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with GLib; see the file COPYING.LIB. If not,
17 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 * Boston, MA 02111-1307, USA.
35 #include <sys/types.h>
49 #define S_ISREG(mode) ((mode)&_S_IFREG)
53 #define S_ISDIR(mode) ((mode)&_S_IFDIR)
56 #endif /* G_OS_WIN32 */
69 #define G_IS_DIR_SEPARATOR(c) (c == G_DIR_SEPARATOR || c == '/')
71 #define G_IS_DIR_SEPARATOR(c) (c == G_DIR_SEPARATOR)
76 * @filename: a filename to test
77 * @test: bitfield of #GFileTest flags
79 * Returns %TRUE if any of the tests in the bitfield @test are
80 * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS |
81 * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists;
82 * the check whether it's a directory doesn't matter since the existence
83 * test is %TRUE. With the current set of available tests, there's no point
84 * passing in more than one test at a time.
86 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
87 * so for a symbolic link to a regular file g_file_test() will return
88 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
90 * Note, that for a dangling symbolic link g_file_test() will return
91 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
93 * You should never use g_file_test() to test whether it is safe
94 * to perform an operaton, because there is always the possibility
95 * of the condition changing before you actually perform the operation.
96 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
97 * to know whether it is is safe to write to a file without being
98 * tricked into writing into a different location. It doesn't work!
100 * <informalexample><programlisting>
101 * /* DON'T DO THIS */
102 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) {
103 * fd = open (filename, O_WRONLY);
104 * /* write to fd */
106 * </programlisting></informalexample>
108 * Another thing to note is that %G_FILE_TEST_EXISTS and
109 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
110 * system call. This usually doesn't matter, but if your program
111 * is setuid or setgid it means that these tests will give you
112 * the answer for the real user ID and group ID , rather than the
113 * effective user ID and group ID.
115 * Return value: whether a test was %TRUE
118 g_file_test (const gchar *filename,
121 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
125 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
130 /* For root, on some POSIX systems, access (filename, X_OK)
131 * will succeed even if no executable bits are set on the
132 * file. We fall through to a stat test to avoid that.
136 test &= ~G_FILE_TEST_IS_EXECUTABLE;
139 if (test & G_FILE_TEST_IS_SYMLINK)
142 /* no sym links on win32, no lstat in msvcrt */
146 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
151 if (test & (G_FILE_TEST_IS_REGULAR |
153 G_FILE_TEST_IS_EXECUTABLE))
157 if (stat (filename, &s) == 0)
159 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
162 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
166 /* The extra test for root when access (file, X_OK) succeeds.
167 * Probably only makes sense on Unix.
169 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
170 ((s.st_mode & S_IXOTH) ||
171 (s.st_mode & S_IXUSR) ||
172 (s.st_mode & S_IXGRP)))
175 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
176 (s.st_mode & _S_IEXEC))
186 g_file_error_quark (void)
190 q = g_quark_from_static_string ("g-file-error-quark");
196 * g_file_error_from_errno:
197 * @err_no: an "errno" value
199 * Gets a #GFileError constant based on the passed-in @errno.
200 * For example, if you pass in %EEXIST this function returns
201 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
202 * assume that all #GFileError values will exist.
204 * Normally a #GFileError value goes into a #GError returned
205 * from a function that manipulates files. So you would use
206 * g_file_error_from_errno() when constructing a #GError.
208 * Return value: #GFileError corresponding to the given @errno
211 g_file_error_from_errno (gint err_no)
217 return G_FILE_ERROR_EXIST;
223 return G_FILE_ERROR_ISDIR;
229 return G_FILE_ERROR_ACCES;
235 return G_FILE_ERROR_NAMETOOLONG;
241 return G_FILE_ERROR_NOENT;
247 return G_FILE_ERROR_NOTDIR;
253 return G_FILE_ERROR_NXIO;
259 return G_FILE_ERROR_NODEV;
265 return G_FILE_ERROR_ROFS;
271 return G_FILE_ERROR_TXTBSY;
277 return G_FILE_ERROR_FAULT;
283 return G_FILE_ERROR_LOOP;
289 return G_FILE_ERROR_NOSPC;
295 return G_FILE_ERROR_NOMEM;
301 return G_FILE_ERROR_MFILE;
307 return G_FILE_ERROR_NFILE;
313 return G_FILE_ERROR_BADF;
319 return G_FILE_ERROR_INVAL;
325 return G_FILE_ERROR_PIPE;
331 return G_FILE_ERROR_AGAIN;
337 return G_FILE_ERROR_INTR;
343 return G_FILE_ERROR_IO;
349 return G_FILE_ERROR_PERM;
355 return G_FILE_ERROR_NOSYS;
360 return G_FILE_ERROR_FAILED;
366 get_contents_stdio (const gchar *filename,
376 size_t total_allocated;
378 g_assert (f != NULL);
380 #define STARTING_ALLOC 64
383 total_allocated = STARTING_ALLOC;
384 str = g_malloc (STARTING_ALLOC);
388 bytes = fread (buf, 1, 2048, f);
390 while ((total_bytes + bytes + 1) > total_allocated)
392 total_allocated *= 2;
393 str = g_try_realloc (str, total_allocated);
397 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
402 _("Could not allocate %lu bytes to read file \"%s\""),
403 (gulong) total_allocated,
404 utf8_filename ? utf8_filename : "???");
405 g_free (utf8_filename);
413 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
417 g_file_error_from_errno (errno),
418 _("Error reading file '%s': %s"),
419 utf8_filename ? utf8_filename : "???",
421 g_free (utf8_filename);
426 memcpy (str + total_bytes, buf, bytes);
427 total_bytes += bytes;
432 str[total_bytes] = '\0';
435 *length = total_bytes;
452 get_contents_regfile (const gchar *filename,
453 struct stat *stat_buf,
464 size = stat_buf->st_size;
466 alloc_size = size + 1;
467 buf = g_try_malloc (alloc_size);
471 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
476 _("Could not allocate %lu bytes to read file \"%s\""),
478 utf8_filename ? utf8_filename : "???");
479 g_free (utf8_filename);
485 while (bytes_read < size)
489 rc = read (fd, buf + bytes_read, size - bytes_read);
496 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
500 g_file_error_from_errno (errno),
501 _("Failed to read from file '%s': %s"),
502 utf8_filename ? utf8_filename : "???",
504 g_free (utf8_filename);
515 buf[bytes_read] = '\0';
518 *length = bytes_read;
534 get_contents_posix (const gchar *filename,
539 struct stat stat_buf;
542 /* O_BINARY useful on Cygwin */
543 fd = open (filename, O_RDONLY|O_BINARY);
547 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
551 g_file_error_from_errno (errno),
552 _("Failed to open file '%s': %s"),
553 utf8_filename ? utf8_filename : "???",
555 g_free (utf8_filename);
560 /* I don't think this will ever fail, aside from ENOMEM, but. */
561 if (fstat (fd, &stat_buf) < 0)
565 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
569 g_file_error_from_errno (errno),
570 _("Failed to get attributes of file '%s': fstat() failed: %s"),
571 utf8_filename ? utf8_filename : "???",
573 g_free (utf8_filename);
578 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
580 return get_contents_regfile (filename,
591 f = fdopen (fd, "r");
595 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
600 g_file_error_from_errno (errno),
601 _("Failed to open file '%s': fdopen() failed: %s"),
602 utf8_filename ? utf8_filename : "???",
604 g_free (utf8_filename);
609 return get_contents_stdio (filename, f, contents, length, error);
613 #else /* G_OS_WIN32 */
616 get_contents_win32 (const gchar *filename,
623 /* I guess you want binary mode; maybe you want text sometimes? */
624 f = fopen (filename, "rb");
628 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
633 g_file_error_from_errno (errno),
634 _("Failed to open file '%s': %s"),
635 utf8_filename ? utf8_filename : "???",
637 g_free (utf8_filename);
642 return get_contents_stdio (filename, f, contents, length, error);
648 * g_file_get_contents:
649 * @filename: a file to read contents from
650 * @contents: location to store an allocated string
651 * @length: location to store length in bytes of the contents
652 * @error: return location for a #GError
654 * Reads an entire file into allocated memory, with good error
655 * checking. If @error is set, %FALSE is returned, and @contents is set
656 * to %NULL. If %TRUE is returned, @error will not be set, and @contents
657 * will be set to the file contents. The string stored in @contents
658 * will be nul-terminated, so for text files you can pass %NULL for the
659 * @length argument. The error domain is #G_FILE_ERROR. Possible
660 * error codes are those in the #GFileError enumeration.
662 * Return value: %TRUE on success, %FALSE if error is set
665 g_file_get_contents (const gchar *filename,
670 g_return_val_if_fail (filename != NULL, FALSE);
671 g_return_val_if_fail (contents != NULL, FALSE);
678 return get_contents_win32 (filename, contents, length, error);
680 return get_contents_posix (filename, contents, length, error);
685 * mkstemp() implementation is from the GNU C library.
686 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
690 * @tmpl: template filename
692 * Opens a temporary file. See the mkstemp() documentation
693 * on most UNIX-like systems. This is a portability wrapper, which simply calls
694 * mkstemp() on systems that have it, and implements
695 * it in GLib otherwise.
697 * The parameter is a string that should match the rules for
698 * mkstemp(), i.e. end in "XXXXXX". The X string will
699 * be modified to form the name of a file that didn't exist.
701 * Return value: A file handle (as from open()) to the file
702 * opened for reading and writing. The file is opened in binary mode
703 * on platforms where there is a difference. The file handle should be
704 * closed with close(). In case of errors, -1 is returned.
707 g_mkstemp (gchar *tmpl)
710 return mkstemp (tmpl);
715 static const char letters[] =
716 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
717 static const int NLETTERS = sizeof (letters) - 1;
720 static int counter = 0;
723 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
726 /* This is where the Xs start. */
727 XXXXXX = &tmpl[len - 6];
729 /* Get some more or less random data. */
730 g_get_current_time (&tv);
731 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
733 for (count = 0; count < 100; value += 7777, ++count)
737 /* Fill in the random bits. */
738 XXXXXX[0] = letters[v % NLETTERS];
740 XXXXXX[1] = letters[v % NLETTERS];
742 XXXXXX[2] = letters[v % NLETTERS];
744 XXXXXX[3] = letters[v % NLETTERS];
746 XXXXXX[4] = letters[v % NLETTERS];
748 XXXXXX[5] = letters[v % NLETTERS];
750 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
754 else if (errno != EEXIST)
755 /* Any other error will apply also to other names we might
756 * try, and there are 2^32 or so of them, so give up now.
761 /* We got out of the loop because we ran out of combinations to try. */
768 * @tmpl: Template for file name, as in g_mkstemp(), basename only
769 * @name_used: location to store actual name used
770 * @error: return location for a #GError
772 * Opens a file for writing in the preferred directory for temporary
773 * files (as returned by g_get_tmp_dir()).
775 * @tmpl should be a string ending with six 'X' characters, as the
776 * parameter to g_mkstemp() (or mkstemp()).
777 * However, unlike these functions, the template should only be a
778 * basename, no directory components are allowed. If template is %NULL,
779 * a default template is used.
781 * Note that in contrast to g_mkstemp() (and mkstemp())
782 * @tmpl is not modified, and might thus be a read-only literal string.
784 * The actual name used is returned in @name_used if non-%NULL. This
785 * string should be freed with g_free() when not needed any longer.
787 * Return value: A file handle (as from open()) to
788 * the file opened for reading and writing. The file is opened in binary
789 * mode on platforms where there is a difference. The file handle should be
790 * closed with close(). In case of errors, -1 is returned
791 * and @error will be set.
794 g_file_open_tmp (const gchar *tmpl,
807 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
809 || (strchr (tmpl, '/') != NULL && (slash = "/"))
820 _("Template '%s' invalid, should not contain a '%s'"),
826 if (strlen (tmpl) < 6 ||
827 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
832 _("Template '%s' doesn't end with XXXXXX"),
837 tmpdir = g_get_tmp_dir ();
839 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
842 sep = G_DIR_SEPARATOR_S;
844 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
846 retval = g_mkstemp (fulltemplate);
852 g_file_error_from_errno (errno),
853 _("Failed to create file '%s': %s"),
854 fulltemplate, g_strerror (errno));
855 g_free (fulltemplate);
860 *name_used = fulltemplate;
862 g_free (fulltemplate);
868 g_build_pathv (const gchar *separator,
869 const gchar *first_element,
873 gint separator_len = strlen (separator);
874 gboolean is_first = TRUE;
875 gboolean have_leading = FALSE;
876 const gchar *single_element = NULL;
877 const gchar *next_element;
878 const gchar *last_trailing = NULL;
880 result = g_string_new (NULL);
882 next_element = first_element;
886 const gchar *element;
892 element = next_element;
893 next_element = va_arg (args, gchar *);
898 /* Ignore empty elements */
907 strncmp (start, separator, separator_len) == 0)
908 start += separator_len;
911 end = start + strlen (start);
915 while (end >= start + separator_len &&
916 strncmp (end - separator_len, separator, separator_len) == 0)
917 end -= separator_len;
920 while (last_trailing >= element + separator_len &&
921 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
922 last_trailing -= separator_len;
926 /* If the leading and trailing separator strings are in the
927 * same element and overlap, the result is exactly that element
929 if (last_trailing <= start)
930 single_element = element;
932 g_string_append_len (result, element, start - element);
936 single_element = NULL;
943 g_string_append (result, separator);
945 g_string_append_len (result, start, end - start);
951 g_string_free (result, TRUE);
952 return g_strdup (single_element);
957 g_string_append (result, last_trailing);
959 return g_string_free (result, FALSE);
965 * @separator: a string used to separator the elements of the path.
966 * @first_element: the first element in the path
967 * @Varargs: remaining elements in path, terminated by %NULL
969 * Creates a path from a series of elements using @separator as the
970 * separator between elements. At the boundary between two elements,
971 * any trailing occurrences of separator in the first element, or
972 * leading occurrences of separator in the second element are removed
973 * and exactly one copy of the separator is inserted.
975 * Empty elements are ignored.
977 * The number of leading copies of the separator on the result is
978 * the same as the number of leading copies of the separator on
979 * the first non-empty element.
981 * The number of trailing copies of the separator on the result is
982 * the same as the number of trailing copies of the separator on
983 * the last non-empty element. (Determination of the number of
984 * trailing copies is done without stripping leading copies, so
985 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
986 * has 1 trailing copy.)
988 * However, if there is only a single non-empty element, and there
989 * are no characters in that element not part of the leading or
990 * trailing separators, then the result is exactly the original value
993 * Other than for determination of the number of leading and trailing
994 * copies of the separator, elements consisting only of copies
995 * of the separator are ignored.
997 * Return value: a newly-allocated string that must be freed with g_free().
1000 g_build_path (const gchar *separator,
1001 const gchar *first_element,
1007 g_return_val_if_fail (separator != NULL, NULL);
1009 va_start (args, first_element);
1010 str = g_build_pathv (separator, first_element, args);
1018 * @first_element: the first element in the path
1019 * @Varargs: remaining elements in path, terminated by %NULL
1021 * Creates a filename from a series of elements using the correct
1022 * separator for filenames.
1024 * On Unix, this function behaves identically to <literal>g_build_path
1025 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1027 * On Windows, it takes into account that either the backslash
1028 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1029 * as separator in filenames, but otherwise behaves as on Unix. When
1030 * file pathname separators need to be inserted, the one that last
1031 * previously occurred in the parameters (reading from left to right)
1034 * No attempt is made to force the resulting filename to be an absolute
1035 * path. If the first element is a relative path, the result will
1036 * be a relative path.
1038 * Return value: a newly-allocated string that must be freed with g_free().
1041 g_build_filename (const gchar *first_element,
1048 va_start (args, first_element);
1049 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
1054 /* Code copied from g_build_pathv(), and modifed to use two
1055 * alternative single-character separators.
1059 gboolean is_first = TRUE;
1060 gboolean have_leading = FALSE;
1061 const gchar *single_element = NULL;
1062 const gchar *next_element;
1063 const gchar *last_trailing = NULL;
1064 gchar current_separator = '\\';
1066 va_start (args, first_element);
1068 result = g_string_new (NULL);
1070 next_element = first_element;
1074 const gchar *element;
1080 element = next_element;
1081 next_element = va_arg (args, gchar *);
1086 /* Ignore empty elements */
1095 (*start == '\\' || *start == '/'))
1097 current_separator = *start;
1102 end = start + strlen (start);
1106 while (end >= start + 1 &&
1107 (end[-1] == '\\' || end[-1] == '/'))
1109 current_separator = end[-1];
1113 last_trailing = end;
1114 while (last_trailing >= element + 1 &&
1115 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1120 /* If the leading and trailing separator strings are in the
1121 * same element and overlap, the result is exactly that element
1123 if (last_trailing <= start)
1124 single_element = element;
1126 g_string_append_len (result, element, start - element);
1127 have_leading = TRUE;
1130 single_element = NULL;
1137 g_string_append_len (result, ¤t_separator, 1);
1139 g_string_append_len (result, start, end - start);
1147 g_string_free (result, TRUE);
1148 return g_strdup (single_element);
1153 g_string_append (result, last_trailing);
1155 return g_string_free (result, FALSE);
1162 * @filename: the symbolic link
1163 * @error: return location for a #GError
1165 * Reads the contents of the symbolic link @filename like the POSIX readlink() function.
1166 * The returned string is in the encoding used for filenames. Use g_filename_to_utf8() to
1167 * convert it to UTF-8.
1169 * Returns: A newly allocated string with the contents of the symbolic link,
1170 * or %NULL if an error occurred.
1175 g_file_read_link (const gchar *filename,
1178 #ifdef HAVE_READLINK
1184 buffer = g_malloc (size);
1188 read_size = readlink (filename, buffer, size);
1189 if (read_size < 0) {
1192 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
1196 g_file_error_from_errno (errno),
1197 _("Failed to read the symbolic link '%s': %s"),
1198 utf8_filename ? utf8_filename : "???",
1199 g_strerror (errno));
1200 g_free (utf8_filename);
1205 if (read_size < size)
1207 buffer[read_size] = 0;
1212 buffer = g_realloc (buffer, size);
1218 _("Symbolic links not supported"));