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.
34 #include <sys/types.h>
48 #define S_ISREG(mode) ((mode)&_S_IFREG)
52 #define S_ISDIR(mode) ((mode)&_S_IFDIR)
55 #endif /* G_OS_WIN32 */
68 #define G_IS_DIR_SEPARATOR(c) (c == G_DIR_SEPARATOR || c == '/')
70 #define G_IS_DIR_SEPARATOR(c) (c == G_DIR_SEPARATOR)
75 * @filename: a filename to test
76 * @test: bitfield of #GFileTest flags
78 * Returns %TRUE if any of the tests in the bitfield @test are
79 * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS |
80 * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists;
81 * the check whether it's a directory doesn't matter since the existence
82 * test is %TRUE. With the current set of available tests, there's no point
83 * passing in more than one test at a time.
85 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
86 * so for a symbolic link to a regular file g_file_test() will return
87 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
89 * Note, that for a dangling symbolic link g_file_test() will return
90 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
92 * You should never use g_file_test() to test whether it is safe
93 * to perform an operaton, because there is always the possibility
94 * of the condition changing before you actually perform the operation.
95 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
96 * to know whether it is is safe to write to a file without being
97 * tricked into writing into a different location. It doesn't work!
99 * <informalexample><programlisting>
100 * /* DON'T DO THIS */
101 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) {
102 * fd = open (filename, O_WRONLY);
103 * /* write to fd */
105 * </programlisting></informalexample>
107 * Another thing to note is that %G_FILE_TEST_EXISTS and
108 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
109 * system call. This usually doesn't matter, but if your program
110 * is setuid or setgid it means that these tests will give you
111 * the answer for the real user ID and group ID , rather than the
112 * effective user ID and group ID.
114 * Return value: whether a test was %TRUE
117 g_file_test (const gchar *filename,
120 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
124 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
129 /* For root, on some POSIX systems, access (filename, X_OK)
130 * will succeed even if no executable bits are set on the
131 * file. We fall through to a stat test to avoid that.
135 test &= ~G_FILE_TEST_IS_EXECUTABLE;
138 if (test & G_FILE_TEST_IS_SYMLINK)
141 /* no sym links on win32, no lstat in msvcrt */
145 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
150 if (test & (G_FILE_TEST_IS_REGULAR |
152 G_FILE_TEST_IS_EXECUTABLE))
156 if (stat (filename, &s) == 0)
158 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
161 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
165 /* The extra test for root when access (file, X_OK) succeeds.
166 * Probably only makes sense on Unix.
168 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
169 ((s.st_mode & S_IXOTH) ||
170 (s.st_mode & S_IXUSR) ||
171 (s.st_mode & S_IXGRP)))
174 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
175 (s.st_mode & _S_IEXEC))
185 g_file_error_quark (void)
189 q = g_quark_from_static_string ("g-file-error-quark");
195 * g_file_error_from_errno:
196 * @err_no: an "errno" value
198 * Gets a #GFileError constant based on the passed-in @errno.
199 * For example, if you pass in %EEXIST this function returns
200 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
201 * assume that all #GFileError values will exist.
203 * Normally a #GFileError value goes into a #GError returned
204 * from a function that manipulates files. So you would use
205 * g_file_error_from_errno() when constructing a #GError.
207 * Return value: #GFileError corresponding to the given @errno
210 g_file_error_from_errno (gint err_no)
216 return G_FILE_ERROR_EXIST;
222 return G_FILE_ERROR_ISDIR;
228 return G_FILE_ERROR_ACCES;
234 return G_FILE_ERROR_NAMETOOLONG;
240 return G_FILE_ERROR_NOENT;
246 return G_FILE_ERROR_NOTDIR;
252 return G_FILE_ERROR_NXIO;
258 return G_FILE_ERROR_NODEV;
264 return G_FILE_ERROR_ROFS;
270 return G_FILE_ERROR_TXTBSY;
276 return G_FILE_ERROR_FAULT;
282 return G_FILE_ERROR_LOOP;
288 return G_FILE_ERROR_NOSPC;
294 return G_FILE_ERROR_NOMEM;
300 return G_FILE_ERROR_MFILE;
306 return G_FILE_ERROR_NFILE;
312 return G_FILE_ERROR_BADF;
318 return G_FILE_ERROR_INVAL;
324 return G_FILE_ERROR_PIPE;
330 return G_FILE_ERROR_AGAIN;
336 return G_FILE_ERROR_INTR;
342 return G_FILE_ERROR_IO;
348 return G_FILE_ERROR_PERM;
353 return G_FILE_ERROR_FAILED;
359 get_contents_stdio (const gchar *filename,
369 size_t total_allocated;
371 g_assert (f != NULL);
373 #define STARTING_ALLOC 64
376 total_allocated = STARTING_ALLOC;
377 str = g_malloc (STARTING_ALLOC);
381 bytes = fread (buf, 1, 2048, f);
383 while ((total_bytes + bytes + 1) > total_allocated)
385 total_allocated *= 2;
386 str = g_try_realloc (str, total_allocated);
393 _("Could not allocate %lu bytes to read file \"%s\""),
394 (gulong) total_allocated, filename);
403 g_file_error_from_errno (errno),
404 _("Error reading file '%s': %s"),
405 filename, g_strerror (errno));
410 memcpy (str + total_bytes, buf, bytes);
411 total_bytes += bytes;
416 str[total_bytes] = '\0';
419 *length = total_bytes;
436 get_contents_regfile (const gchar *filename,
437 struct stat *stat_buf,
448 size = stat_buf->st_size;
450 alloc_size = size + 1;
451 buf = g_try_malloc (alloc_size);
458 _("Could not allocate %lu bytes to read file \"%s\""),
459 (gulong) alloc_size, filename);
465 while (bytes_read < size)
469 rc = read (fd, buf + bytes_read, size - bytes_read);
479 g_file_error_from_errno (errno),
480 _("Failed to read from file '%s': %s"),
481 filename, g_strerror (errno));
492 buf[bytes_read] = '\0';
495 *length = bytes_read;
511 get_contents_posix (const gchar *filename,
516 struct stat stat_buf;
519 /* O_BINARY useful on Cygwin */
520 fd = open (filename, O_RDONLY|O_BINARY);
526 g_file_error_from_errno (errno),
527 _("Failed to open file '%s': %s"),
528 filename, g_strerror (errno));
533 /* I don't think this will ever fail, aside from ENOMEM, but. */
534 if (fstat (fd, &stat_buf) < 0)
540 g_file_error_from_errno (errno),
541 _("Failed to get attributes of file '%s': fstat() failed: %s"),
542 filename, g_strerror (errno));
547 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
549 return get_contents_regfile (filename,
560 f = fdopen (fd, "r");
566 g_file_error_from_errno (errno),
567 _("Failed to open file '%s': fdopen() failed: %s"),
568 filename, g_strerror (errno));
573 return get_contents_stdio (filename, f, contents, length, error);
577 #else /* G_OS_WIN32 */
580 get_contents_win32 (const gchar *filename,
587 /* I guess you want binary mode; maybe you want text sometimes? */
588 f = fopen (filename, "rb");
594 g_file_error_from_errno (errno),
595 _("Failed to open file '%s': %s"),
596 filename, g_strerror (errno));
601 return get_contents_stdio (filename, f, contents, length, error);
607 * g_file_get_contents:
608 * @filename: a file to read contents from
609 * @contents: location to store an allocated string
610 * @length: location to store length in bytes of the contents
611 * @error: return location for a #GError
613 * Reads an entire file into allocated memory, with good error
614 * checking. If @error is set, %FALSE is returned, and @contents is set
615 * to %NULL. If %TRUE is returned, @error will not be set, and @contents
616 * will be set to the file contents. The string stored in @contents
617 * will be nul-terminated, so for text files you can pass %NULL for the
618 * @length argument. The error domain is #G_FILE_ERROR. Possible
619 * error codes are those in the #GFileError enumeration.
621 * Return value: %TRUE on success, %FALSE if error is set
624 g_file_get_contents (const gchar *filename,
629 g_return_val_if_fail (filename != NULL, FALSE);
630 g_return_val_if_fail (contents != NULL, FALSE);
637 return get_contents_win32 (filename, contents, length, error);
639 return get_contents_posix (filename, contents, length, error);
644 * mkstemp() implementation is from the GNU C library.
645 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
649 * @tmpl: template filename
651 * Opens a temporary file. See the mkstemp() documentation
652 * on most UNIX-like systems. This is a portability wrapper, which simply calls
653 * mkstemp() on systems that have it, and implements
654 * it in GLib otherwise.
656 * The parameter is a string that should match the rules for
657 * mkstemp(), i.e. end in "XXXXXX". The X string will
658 * be modified to form the name of a file that didn't exist.
660 * Return value: A file handle (as from open()) to the file
661 * opened for reading and writing. The file is opened in binary mode
662 * on platforms where there is a difference. The file handle should be
663 * closed with close(). In case of errors, -1 is returned.
666 g_mkstemp (gchar *tmpl)
669 return mkstemp (tmpl);
674 static const char letters[] =
675 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
676 static const int NLETTERS = sizeof (letters) - 1;
679 static int counter = 0;
682 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
685 /* This is where the Xs start. */
686 XXXXXX = &tmpl[len - 6];
688 /* Get some more or less random data. */
689 g_get_current_time (&tv);
690 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
692 for (count = 0; count < 100; value += 7777, ++count)
696 /* Fill in the random bits. */
697 XXXXXX[0] = letters[v % NLETTERS];
699 XXXXXX[1] = letters[v % NLETTERS];
701 XXXXXX[2] = letters[v % NLETTERS];
703 XXXXXX[3] = letters[v % NLETTERS];
705 XXXXXX[4] = letters[v % NLETTERS];
707 XXXXXX[5] = letters[v % NLETTERS];
709 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
713 else if (errno != EEXIST)
714 /* Any other error will apply also to other names we might
715 * try, and there are 2^32 or so of them, so give up now.
720 /* We got out of the loop because we ran out of combinations to try. */
727 * @tmpl: Template for file name, as in g_mkstemp(), basename only
728 * @name_used: location to store actual name used
729 * @error: return location for a #GError
731 * Opens a file for writing in the preferred directory for temporary
732 * files (as returned by g_get_tmp_dir()).
734 * @tmpl should be a string ending with six 'X' characters, as the
735 * parameter to g_mkstemp() (or mkstemp()).
736 * However, unlike these functions, the template should only be a
737 * basename, no directory components are allowed. If template is %NULL,
738 * a default template is used.
740 * Note that in contrast to g_mkstemp() (and mkstemp())
741 * @tmpl is not modified, and might thus be a read-only literal string.
743 * The actual name used is returned in @name_used if non-%NULL. This
744 * string should be freed with g_free() when not needed any longer.
746 * Return value: A file handle (as from open()) to
747 * the file opened for reading and writing. The file is opened in binary
748 * mode on platforms where there is a difference. The file handle should be
749 * closed with close(). In case of errors, -1 is returned
750 * and @error will be set.
753 g_file_open_tmp (const gchar *tmpl,
766 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
768 || (strchr (tmpl, '/') != NULL && (slash = "/"))
779 _("Template '%s' invalid, should not contain a '%s'"),
785 if (strlen (tmpl) < 6 ||
786 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
791 _("Template '%s' doesn't end with XXXXXX"),
796 tmpdir = g_get_tmp_dir ();
798 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
801 sep = G_DIR_SEPARATOR_S;
803 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
805 retval = g_mkstemp (fulltemplate);
811 g_file_error_from_errno (errno),
812 _("Failed to create file '%s': %s"),
813 fulltemplate, g_strerror (errno));
814 g_free (fulltemplate);
819 *name_used = fulltemplate;
821 g_free (fulltemplate);
827 g_build_pathv (const gchar *separator,
828 const gchar *first_element,
832 gint separator_len = strlen (separator);
833 gboolean is_first = TRUE;
834 gboolean have_leading = FALSE;
835 const gchar *single_element = NULL;
836 const gchar *next_element;
837 const gchar *last_trailing = NULL;
839 result = g_string_new (NULL);
841 next_element = first_element;
845 const gchar *element;
851 element = next_element;
852 next_element = va_arg (args, gchar *);
857 /* Ignore empty elements */
866 strncmp (start, separator, separator_len) == 0)
867 start += separator_len;
870 end = start + strlen (start);
874 while (end >= start + separator_len &&
875 strncmp (end - separator_len, separator, separator_len) == 0)
876 end -= separator_len;
879 while (last_trailing >= element + separator_len &&
880 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
881 last_trailing -= separator_len;
885 /* If the leading and trailing separator strings are in the
886 * same element and overlap, the result is exactly that element
888 if (last_trailing <= start)
889 single_element = element;
891 g_string_append_len (result, element, start - element);
895 single_element = NULL;
902 g_string_append (result, separator);
904 g_string_append_len (result, start, end - start);
910 g_string_free (result, TRUE);
911 return g_strdup (single_element);
916 g_string_append (result, last_trailing);
918 return g_string_free (result, FALSE);
924 * @separator: a string used to separator the elements of the path.
925 * @first_element: the first element in the path
926 * @Varargs: remaining elements in path, terminated by %NULL
928 * Creates a path from a series of elements using @separator as the
929 * separator between elements. At the boundary between two elements,
930 * any trailing occurrences of separator in the first element, or
931 * leading occurrences of separator in the second element are removed
932 * and exactly one copy of the separator is inserted.
934 * Empty elements are ignored.
936 * The number of leading copies of the separator on the result is
937 * the same as the number of leading copies of the separator on
938 * the first non-empty element.
940 * The number of trailing copies of the separator on the result is
941 * the same as the number of trailing copies of the separator on
942 * the last non-empty element. (Determination of the number of
943 * trailing copies is done without stripping leading copies, so
944 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
945 * has 1 trailing copy.)
947 * However, if there is only a single non-empty element, and there
948 * are no characters in that element not part of the leading or
949 * trailing separators, then the result is exactly the original value
952 * Other than for determination of the number of leading and trailing
953 * copies of the separator, elements consisting only of copies
954 * of the separator are ignored.
956 * Return value: a newly-allocated string that must be freed with g_free().
959 g_build_path (const gchar *separator,
960 const gchar *first_element,
966 g_return_val_if_fail (separator != NULL, NULL);
968 va_start (args, first_element);
969 str = g_build_pathv (separator, first_element, args);
977 * @first_element: the first element in the path
978 * @Varargs: remaining elements in path, terminated by %NULL
980 * Creates a filename from a series of elements using the correct
981 * separator for filenames.
983 * On Unix, this function behaves identically to <literal>g_build_path
984 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
986 * On Windows, it takes into account that either the backslash
987 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
988 * as separator in filenames, but otherwise behaves as on Unix. When
989 * file pathname separators need to be inserted, the one that last
990 * previously occurred in the parameters (reading from left to right)
993 * No attempt is made to force the resulting filename to be an absolute
994 * path. If the first element is a relative path, the result will
995 * be a relative path.
997 * Return value: a newly-allocated string that must be freed with g_free().
1000 g_build_filename (const gchar *first_element,
1007 va_start (args, first_element);
1008 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
1013 /* Code copied from g_build_pathv(), and modifed to use two
1014 * alternative single-character separators.
1018 gboolean is_first = TRUE;
1019 gboolean have_leading = FALSE;
1020 const gchar *single_element = NULL;
1021 const gchar *next_element;
1022 const gchar *last_trailing = NULL;
1023 gchar current_separator = '\\';
1025 va_start (args, first_element);
1027 result = g_string_new (NULL);
1029 next_element = first_element;
1033 const gchar *element;
1039 element = next_element;
1040 next_element = va_arg (args, gchar *);
1045 /* Ignore empty elements */
1054 (*start == '\\' || *start == '/'))
1056 current_separator = *start;
1061 end = start + strlen (start);
1065 while (end >= start + 1 &&
1066 (end[-1] == '\\' || end[-1] == '/'))
1068 current_separator = end[-1];
1072 last_trailing = end;
1073 while (last_trailing >= element + 1 &&
1074 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1079 /* If the leading and trailing separator strings are in the
1080 * same element and overlap, the result is exactly that element
1082 if (last_trailing <= start)
1083 single_element = element;
1085 g_string_append_len (result, element, start - element);
1086 have_leading = TRUE;
1089 single_element = NULL;
1096 g_string_append_len (result, ¤t_separator, 1);
1098 g_string_append_len (result, start, end - start);
1106 g_string_free (result, TRUE);
1107 return g_strdup (single_element);
1112 g_string_append (result, last_trailing);
1114 return g_string_free (result, FALSE);
1121 * @filename: the symbolic link
1122 * @error: return location for a #GError
1124 * Reads the contents of the symbolic link @filename like the POSIX readlink() function.
1125 * The returned string is in the encoding used for filenames. Use g_filename_to_utf8() to
1126 * convert it to UTF-8.
1128 * Returns: A newly allocated string with the contents of the symbolic link,
1129 * or %NULL if an error occurred.
1134 g_file_read_link (const gchar *filename,
1137 #ifdef HAVE_READLINK
1143 buffer = g_malloc (size);
1147 read_size = readlink (filename, buffer, size);
1148 if (read_size < 0) {
1152 g_file_error_from_errno (errno),
1153 _("Failed to read the symbolic link '%s': %s"),
1154 filename, g_strerror (errno));
1159 if (read_size < size)
1161 buffer[read_size] = 0;
1166 buffer = g_realloc (buffer, size);
1172 _("Symbolic links not supported"));