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);
495 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)
563 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
568 g_file_error_from_errno (errno),
569 _("Failed to get attributes of file '%s': fstat() failed: %s"),
570 utf8_filename ? utf8_filename : "???",
572 g_free (utf8_filename);
577 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
579 return get_contents_regfile (filename,
590 f = fdopen (fd, "r");
594 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
599 g_file_error_from_errno (errno),
600 _("Failed to open file '%s': fdopen() failed: %s"),
601 utf8_filename ? utf8_filename : "???",
603 g_free (utf8_filename);
608 return get_contents_stdio (filename, f, contents, length, error);
612 #else /* G_OS_WIN32 */
615 get_contents_win32 (const gchar *filename,
622 /* I guess you want binary mode; maybe you want text sometimes? */
623 f = fopen (filename, "rb");
627 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
632 g_file_error_from_errno (errno),
633 _("Failed to open file '%s': %s"),
634 utf8_filename ? utf8_filename : "???",
636 g_free (utf8_filename);
641 return get_contents_stdio (filename, f, contents, length, error);
647 * g_file_get_contents:
648 * @filename: a file to read contents from
649 * @contents: location to store an allocated string
650 * @length: location to store length in bytes of the contents
651 * @error: return location for a #GError
653 * Reads an entire file into allocated memory, with good error
654 * checking. If @error is set, %FALSE is returned, and @contents is set
655 * to %NULL. If %TRUE is returned, @error will not be set, and @contents
656 * will be set to the file contents. The string stored in @contents
657 * will be nul-terminated, so for text files you can pass %NULL for the
658 * @length argument. The error domain is #G_FILE_ERROR. Possible
659 * error codes are those in the #GFileError enumeration.
661 * Return value: %TRUE on success, %FALSE if error is set
664 g_file_get_contents (const gchar *filename,
669 g_return_val_if_fail (filename != NULL, FALSE);
670 g_return_val_if_fail (contents != NULL, FALSE);
677 return get_contents_win32 (filename, contents, length, error);
679 return get_contents_posix (filename, contents, length, error);
684 * mkstemp() implementation is from the GNU C library.
685 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
689 * @tmpl: template filename
691 * Opens a temporary file. See the mkstemp() documentation
692 * on most UNIX-like systems. This is a portability wrapper, which simply calls
693 * mkstemp() on systems that have it, and implements
694 * it in GLib otherwise.
696 * The parameter is a string that should match the rules for
697 * mkstemp(), i.e. end in "XXXXXX". The X string will
698 * be modified to form the name of a file that didn't exist.
700 * Return value: A file handle (as from open()) to the file
701 * opened for reading and writing. The file is opened in binary mode
702 * on platforms where there is a difference. The file handle should be
703 * closed with close(). In case of errors, -1 is returned.
706 g_mkstemp (gchar *tmpl)
709 return mkstemp (tmpl);
714 static const char letters[] =
715 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
716 static const int NLETTERS = sizeof (letters) - 1;
719 static int counter = 0;
722 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
725 /* This is where the Xs start. */
726 XXXXXX = &tmpl[len - 6];
728 /* Get some more or less random data. */
729 g_get_current_time (&tv);
730 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
732 for (count = 0; count < 100; value += 7777, ++count)
736 /* Fill in the random bits. */
737 XXXXXX[0] = letters[v % NLETTERS];
739 XXXXXX[1] = letters[v % NLETTERS];
741 XXXXXX[2] = letters[v % NLETTERS];
743 XXXXXX[3] = letters[v % NLETTERS];
745 XXXXXX[4] = letters[v % NLETTERS];
747 XXXXXX[5] = letters[v % NLETTERS];
749 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
753 else if (errno != EEXIST)
754 /* Any other error will apply also to other names we might
755 * try, and there are 2^32 or so of them, so give up now.
760 /* We got out of the loop because we ran out of combinations to try. */
767 * @tmpl: Template for file name, as in g_mkstemp(), basename only
768 * @name_used: location to store actual name used
769 * @error: return location for a #GError
771 * Opens a file for writing in the preferred directory for temporary
772 * files (as returned by g_get_tmp_dir()).
774 * @tmpl should be a string ending with six 'X' characters, as the
775 * parameter to g_mkstemp() (or mkstemp()).
776 * However, unlike these functions, the template should only be a
777 * basename, no directory components are allowed. If template is %NULL,
778 * a default template is used.
780 * Note that in contrast to g_mkstemp() (and mkstemp())
781 * @tmpl is not modified, and might thus be a read-only literal string.
783 * The actual name used is returned in @name_used if non-%NULL. This
784 * string should be freed with g_free() when not needed any longer.
786 * Return value: A file handle (as from open()) to
787 * the file opened for reading and writing. The file is opened in binary
788 * mode on platforms where there is a difference. The file handle should be
789 * closed with close(). In case of errors, -1 is returned
790 * and @error will be set.
793 g_file_open_tmp (const gchar *tmpl,
806 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
808 || (strchr (tmpl, '/') != NULL && (slash = "/"))
819 _("Template '%s' invalid, should not contain a '%s'"),
825 if (strlen (tmpl) < 6 ||
826 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
831 _("Template '%s' doesn't end with XXXXXX"),
836 tmpdir = g_get_tmp_dir ();
838 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
841 sep = G_DIR_SEPARATOR_S;
843 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
845 retval = g_mkstemp (fulltemplate);
851 g_file_error_from_errno (errno),
852 _("Failed to create file '%s': %s"),
853 fulltemplate, g_strerror (errno));
854 g_free (fulltemplate);
859 *name_used = fulltemplate;
861 g_free (fulltemplate);
867 g_build_pathv (const gchar *separator,
868 const gchar *first_element,
872 gint separator_len = strlen (separator);
873 gboolean is_first = TRUE;
874 gboolean have_leading = FALSE;
875 const gchar *single_element = NULL;
876 const gchar *next_element;
877 const gchar *last_trailing = NULL;
879 result = g_string_new (NULL);
881 next_element = first_element;
885 const gchar *element;
891 element = next_element;
892 next_element = va_arg (args, gchar *);
897 /* Ignore empty elements */
906 strncmp (start, separator, separator_len) == 0)
907 start += separator_len;
910 end = start + strlen (start);
914 while (end >= start + separator_len &&
915 strncmp (end - separator_len, separator, separator_len) == 0)
916 end -= separator_len;
919 while (last_trailing >= element + separator_len &&
920 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
921 last_trailing -= separator_len;
925 /* If the leading and trailing separator strings are in the
926 * same element and overlap, the result is exactly that element
928 if (last_trailing <= start)
929 single_element = element;
931 g_string_append_len (result, element, start - element);
935 single_element = NULL;
942 g_string_append (result, separator);
944 g_string_append_len (result, start, end - start);
950 g_string_free (result, TRUE);
951 return g_strdup (single_element);
956 g_string_append (result, last_trailing);
958 return g_string_free (result, FALSE);
964 * @separator: a string used to separator the elements of the path.
965 * @first_element: the first element in the path
966 * @Varargs: remaining elements in path, terminated by %NULL
968 * Creates a path from a series of elements using @separator as the
969 * separator between elements. At the boundary between two elements,
970 * any trailing occurrences of separator in the first element, or
971 * leading occurrences of separator in the second element are removed
972 * and exactly one copy of the separator is inserted.
974 * Empty elements are ignored.
976 * The number of leading copies of the separator on the result is
977 * the same as the number of leading copies of the separator on
978 * the first non-empty element.
980 * The number of trailing copies of the separator on the result is
981 * the same as the number of trailing copies of the separator on
982 * the last non-empty element. (Determination of the number of
983 * trailing copies is done without stripping leading copies, so
984 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
985 * has 1 trailing copy.)
987 * However, if there is only a single non-empty element, and there
988 * are no characters in that element not part of the leading or
989 * trailing separators, then the result is exactly the original value
992 * Other than for determination of the number of leading and trailing
993 * copies of the separator, elements consisting only of copies
994 * of the separator are ignored.
996 * Return value: a newly-allocated string that must be freed with g_free().
999 g_build_path (const gchar *separator,
1000 const gchar *first_element,
1006 g_return_val_if_fail (separator != NULL, NULL);
1008 va_start (args, first_element);
1009 str = g_build_pathv (separator, first_element, args);
1017 * @first_element: the first element in the path
1018 * @Varargs: remaining elements in path, terminated by %NULL
1020 * Creates a filename from a series of elements using the correct
1021 * separator for filenames.
1023 * On Unix, this function behaves identically to <literal>g_build_path
1024 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1026 * On Windows, it takes into account that either the backslash
1027 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1028 * as separator in filenames, but otherwise behaves as on Unix. When
1029 * file pathname separators need to be inserted, the one that last
1030 * previously occurred in the parameters (reading from left to right)
1033 * No attempt is made to force the resulting filename to be an absolute
1034 * path. If the first element is a relative path, the result will
1035 * be a relative path.
1037 * Return value: a newly-allocated string that must be freed with g_free().
1040 g_build_filename (const gchar *first_element,
1047 va_start (args, first_element);
1048 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
1053 /* Code copied from g_build_pathv(), and modifed to use two
1054 * alternative single-character separators.
1058 gboolean is_first = TRUE;
1059 gboolean have_leading = FALSE;
1060 const gchar *single_element = NULL;
1061 const gchar *next_element;
1062 const gchar *last_trailing = NULL;
1063 gchar current_separator = '\\';
1065 va_start (args, first_element);
1067 result = g_string_new (NULL);
1069 next_element = first_element;
1073 const gchar *element;
1079 element = next_element;
1080 next_element = va_arg (args, gchar *);
1085 /* Ignore empty elements */
1094 (*start == '\\' || *start == '/'))
1096 current_separator = *start;
1101 end = start + strlen (start);
1105 while (end >= start + 1 &&
1106 (end[-1] == '\\' || end[-1] == '/'))
1108 current_separator = end[-1];
1112 last_trailing = end;
1113 while (last_trailing >= element + 1 &&
1114 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1119 /* If the leading and trailing separator strings are in the
1120 * same element and overlap, the result is exactly that element
1122 if (last_trailing <= start)
1123 single_element = element;
1125 g_string_append_len (result, element, start - element);
1126 have_leading = TRUE;
1129 single_element = NULL;
1136 g_string_append_len (result, ¤t_separator, 1);
1138 g_string_append_len (result, start, end - start);
1146 g_string_free (result, TRUE);
1147 return g_strdup (single_element);
1152 g_string_append (result, last_trailing);
1154 return g_string_free (result, FALSE);
1161 * @filename: the symbolic link
1162 * @error: return location for a #GError
1164 * Reads the contents of the symbolic link @filename like the POSIX readlink() function.
1165 * The returned string is in the encoding used for filenames. Use g_filename_to_utf8() to
1166 * convert it to UTF-8.
1168 * Returns: A newly allocated string with the contents of the symbolic link,
1169 * or %NULL if an error occurred.
1174 g_file_read_link (const gchar *filename,
1177 #ifdef HAVE_READLINK
1183 buffer = g_malloc (size);
1187 read_size = readlink (filename, buffer, size);
1188 if (read_size < 0) {
1189 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
1194 g_file_error_from_errno (errno),
1195 _("Failed to read the symbolic link '%s': %s"),
1196 utf8_filename ? utf8_filename : "???",
1197 g_strerror (errno));
1198 g_free (utf8_filename);
1203 if (read_size < size)
1205 buffer[read_size] = 0;
1210 buffer = g_realloc (buffer, size);
1216 _("Symbolic links not supported"));