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>
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))
124 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
131 /* For root, on some POSIX systems, access (filename, X_OK)
132 * will succeed even if no executable bits are set on the
133 * file. We fall through to a stat test to avoid that.
137 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)))
182 g_file_error_quark (void)
186 q = g_quark_from_static_string ("g-file-error-quark");
192 * g_file_error_from_errno:
193 * @err_no: an "errno" value
195 * Gets a #GFileError constant based on the passed-in @errno.
196 * For example, if you pass in %EEXIST this function returns
197 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
198 * assume that all #GFileError values will exist.
200 * Normally a #GFileError value goes into a #GError returned
201 * from a function that manipulates files. So you would use
202 * g_file_error_from_errno() when constructing a #GError.
204 * Return value: #GFileError corresponding to the given @errno
207 g_file_error_from_errno (gint err_no)
213 return G_FILE_ERROR_EXIST;
219 return G_FILE_ERROR_ISDIR;
225 return G_FILE_ERROR_ACCES;
231 return G_FILE_ERROR_NAMETOOLONG;
237 return G_FILE_ERROR_NOENT;
243 return G_FILE_ERROR_NOTDIR;
249 return G_FILE_ERROR_NXIO;
255 return G_FILE_ERROR_NODEV;
261 return G_FILE_ERROR_ROFS;
267 return G_FILE_ERROR_TXTBSY;
273 return G_FILE_ERROR_FAULT;
279 return G_FILE_ERROR_LOOP;
285 return G_FILE_ERROR_NOSPC;
291 return G_FILE_ERROR_NOMEM;
297 return G_FILE_ERROR_MFILE;
303 return G_FILE_ERROR_NFILE;
309 return G_FILE_ERROR_BADF;
315 return G_FILE_ERROR_INVAL;
321 return G_FILE_ERROR_PIPE;
327 return G_FILE_ERROR_AGAIN;
333 return G_FILE_ERROR_INTR;
339 return G_FILE_ERROR_IO;
345 return G_FILE_ERROR_PERM;
350 return G_FILE_ERROR_FAILED;
356 get_contents_stdio (const gchar *filename,
366 size_t total_allocated;
368 g_assert (f != NULL);
370 #define STARTING_ALLOC 64
373 total_allocated = STARTING_ALLOC;
374 str = g_malloc (STARTING_ALLOC);
378 bytes = fread (buf, 1, 2048, f);
380 while ((total_bytes + bytes + 1) > total_allocated)
382 total_allocated *= 2;
383 str = g_try_realloc (str, total_allocated);
390 _("Could not allocate %lu bytes to read file \"%s\""),
391 (gulong) total_allocated, filename);
400 g_file_error_from_errno (errno),
401 _("Error reading file '%s': %s"),
402 filename, g_strerror (errno));
407 memcpy (str + total_bytes, buf, bytes);
408 total_bytes += bytes;
413 str[total_bytes] = '\0';
416 *length = total_bytes;
433 get_contents_regfile (const gchar *filename,
434 struct stat *stat_buf,
445 size = stat_buf->st_size;
447 alloc_size = size + 1;
448 buf = g_try_malloc (alloc_size);
455 _("Could not allocate %lu bytes to read file \"%s\""),
456 (gulong) alloc_size, filename);
462 while (bytes_read < size)
466 rc = read (fd, buf + bytes_read, size - bytes_read);
476 g_file_error_from_errno (errno),
477 _("Failed to read from file '%s': %s"),
478 filename, g_strerror (errno));
489 buf[bytes_read] = '\0';
492 *length = bytes_read;
508 get_contents_posix (const gchar *filename,
513 struct stat stat_buf;
516 /* O_BINARY useful on Cygwin */
517 fd = open (filename, O_RDONLY|O_BINARY);
523 g_file_error_from_errno (errno),
524 _("Failed to open file '%s': %s"),
525 filename, g_strerror (errno));
530 /* I don't think this will ever fail, aside from ENOMEM, but. */
531 if (fstat (fd, &stat_buf) < 0)
537 g_file_error_from_errno (errno),
538 _("Failed to get attributes of file '%s': fstat() failed: %s"),
539 filename, g_strerror (errno));
544 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
546 return get_contents_regfile (filename,
557 f = fdopen (fd, "r");
563 g_file_error_from_errno (errno),
564 _("Failed to open file '%s': fdopen() failed: %s"),
565 filename, g_strerror (errno));
570 return get_contents_stdio (filename, f, contents, length, error);
574 #else /* G_OS_WIN32 */
577 get_contents_win32 (const gchar *filename,
584 /* I guess you want binary mode; maybe you want text sometimes? */
585 f = fopen (filename, "rb");
591 g_file_error_from_errno (errno),
592 _("Failed to open file '%s': %s"),
593 filename, g_strerror (errno));
598 return get_contents_stdio (filename, f, contents, length, error);
604 * g_file_get_contents:
605 * @filename: a file to read contents from
606 * @contents: location to store an allocated string
607 * @length: location to store length in bytes of the contents
608 * @error: return location for a #GError
610 * Reads an entire file into allocated memory, with good error
611 * checking. If @error is set, %FALSE is returned, and @contents is set
612 * to %NULL. If %TRUE is returned, @error will not be set, and @contents
613 * will be set to the file contents. The string stored in @contents
614 * will be nul-terminated, so for text files you can pass %NULL for the
615 * @length argument. The error domain is #G_FILE_ERROR. Possible
616 * error codes are those in the #GFileError enumeration.
618 * Return value: %TRUE on success, %FALSE if error is set
621 g_file_get_contents (const gchar *filename,
626 g_return_val_if_fail (filename != NULL, FALSE);
627 g_return_val_if_fail (contents != NULL, FALSE);
634 return get_contents_win32 (filename, contents, length, error);
636 return get_contents_posix (filename, contents, length, error);
641 * mkstemp() implementation is from the GNU C library.
642 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
646 * @tmpl: template filename
648 * Opens a temporary file. See the mkstemp() documentation
649 * on most UNIX-like systems. This is a portability wrapper, which simply calls
650 * mkstemp() on systems that have it, and implements
651 * it in GLib otherwise.
653 * The parameter is a string that should match the rules for
654 * mkstemp(), i.e. end in "XXXXXX". The X string will
655 * be modified to form the name of a file that didn't exist.
657 * Return value: A file handle (as from open()) to the file
658 * opened for reading and writing. The file is opened in binary mode
659 * on platforms where there is a difference. The file handle should be
660 * closed with close(). In case of errors, -1 is returned.
663 g_mkstemp (gchar *tmpl)
666 return mkstemp (tmpl);
671 static const char letters[] =
672 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
673 static const int NLETTERS = sizeof (letters) - 1;
676 static int counter = 0;
679 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
682 /* This is where the Xs start. */
683 XXXXXX = &tmpl[len - 6];
685 /* Get some more or less random data. */
686 g_get_current_time (&tv);
687 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
689 for (count = 0; count < 100; value += 7777, ++count)
693 /* Fill in the random bits. */
694 XXXXXX[0] = letters[v % NLETTERS];
696 XXXXXX[1] = letters[v % NLETTERS];
698 XXXXXX[2] = letters[v % NLETTERS];
700 XXXXXX[3] = letters[v % NLETTERS];
702 XXXXXX[4] = letters[v % NLETTERS];
704 XXXXXX[5] = letters[v % NLETTERS];
706 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
710 else if (errno != EEXIST)
711 /* Any other error will apply also to other names we might
712 * try, and there are 2^32 or so of them, so give up now.
717 /* We got out of the loop because we ran out of combinations to try. */
724 * @tmpl: Template for file name, as in g_mkstemp(), basename only
725 * @name_used: location to store actual name used
726 * @error: return location for a #GError
728 * Opens a file for writing in the preferred directory for temporary
729 * files (as returned by g_get_tmp_dir()).
731 * @tmpl should be a string ending with six 'X' characters, as the
732 * parameter to g_mkstemp() (or mkstemp()).
733 * However, unlike these functions, the template should only be a
734 * basename, no directory components are allowed. If template is %NULL,
735 * a default template is used.
737 * Note that in contrast to g_mkstemp() (and mkstemp())
738 * @tmpl is not modified, and might thus be a read-only literal string.
740 * The actual name used is returned in @name_used if non-%NULL. This
741 * string should be freed with g_free() when not needed any longer.
743 * Return value: A file handle (as from open()) to
744 * the file opened for reading and writing. The file is opened in binary
745 * mode on platforms where there is a difference. The file handle should be
746 * closed with close(). In case of errors, -1 is returned
747 * and @error will be set.
750 g_file_open_tmp (const gchar *tmpl,
763 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
765 || (strchr (tmpl, '/') != NULL && (slash = "/"))
776 _("Template '%s' invalid, should not contain a '%s'"),
782 if (strlen (tmpl) < 6 ||
783 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
788 _("Template '%s' doesn't end with XXXXXX"),
793 tmpdir = g_get_tmp_dir ();
795 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
798 sep = G_DIR_SEPARATOR_S;
800 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
802 retval = g_mkstemp (fulltemplate);
808 g_file_error_from_errno (errno),
809 _("Failed to create file '%s': %s"),
810 fulltemplate, g_strerror (errno));
811 g_free (fulltemplate);
816 *name_used = fulltemplate;
818 g_free (fulltemplate);
824 g_build_pathv (const gchar *separator,
825 const gchar *first_element,
829 gint separator_len = strlen (separator);
830 gboolean is_first = TRUE;
831 gboolean have_leading = FALSE;
832 const gchar *single_element = NULL;
833 const gchar *next_element;
834 const gchar *last_trailing = NULL;
836 result = g_string_new (NULL);
838 next_element = first_element;
842 const gchar *element;
848 element = next_element;
849 next_element = va_arg (args, gchar *);
854 /* Ignore empty elements */
863 strncmp (start, separator, separator_len) == 0)
864 start += separator_len;
867 end = start + strlen (start);
871 while (end >= start + separator_len &&
872 strncmp (end - separator_len, separator, separator_len) == 0)
873 end -= separator_len;
876 while (last_trailing >= element + separator_len &&
877 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
878 last_trailing -= separator_len;
882 /* If the leading and trailing separator strings are in the
883 * same element and overlap, the result is exactly that element
885 if (last_trailing <= start)
886 single_element = element;
888 g_string_append_len (result, element, start - element);
892 single_element = NULL;
899 g_string_append (result, separator);
901 g_string_append_len (result, start, end - start);
907 g_string_free (result, TRUE);
908 return g_strdup (single_element);
913 g_string_append (result, last_trailing);
915 return g_string_free (result, FALSE);
921 * @separator: a string used to separator the elements of the path.
922 * @first_element: the first element in the path
923 * @Varargs: remaining elements in path, terminated by %NULL
925 * Creates a path from a series of elements using @separator as the
926 * separator between elements. At the boundary between two elements,
927 * any trailing occurrences of separator in the first element, or
928 * leading occurrences of separator in the second element are removed
929 * and exactly one copy of the separator is inserted.
931 * Empty elements are ignored.
933 * The number of leading copies of the separator on the result is
934 * the same as the number of leading copies of the separator on
935 * the first non-empty element.
937 * The number of trailing copies of the separator on the result is
938 * the same as the number of trailing copies of the separator on
939 * the last non-empty element. (Determination of the number of
940 * trailing copies is done without stripping leading copies, so
941 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
942 * has 1 trailing copy.)
944 * However, if there is only a single non-empty element, and there
945 * are no characters in that element not part of the leading or
946 * trailing separators, then the result is exactly the original value
949 * Other than for determination of the number of leading and trailing
950 * copies of the separator, elements consisting only of copies
951 * of the separator are ignored.
953 * Return value: a newly-allocated string that must be freed with g_free().
956 g_build_path (const gchar *separator,
957 const gchar *first_element,
963 g_return_val_if_fail (separator != NULL, NULL);
965 va_start (args, first_element);
966 str = g_build_pathv (separator, first_element, args);
974 * @first_element: the first element in the path
975 * @Varargs: remaining elements in path, terminated by %NULL
977 * Creates a filename from a series of elements using the correct
978 * separator for filenames.
980 * On Unix, this function behaves identically to <literal>g_build_path
981 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
983 * On Windows, it takes into account that either the backslash
984 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
985 * as separator in filenames, but otherwise behaves as on Unix. When
986 * file pathname separators need to be inserted, the one that last
987 * previously occurred in the parameters (reading from left to right)
990 * No attempt is made to force the resulting filename to be an absolute
991 * path. If the first element is a relative path, the result will
992 * be a relative path.
994 * Return value: a newly-allocated string that must be freed with g_free().
997 g_build_filename (const gchar *first_element,
1004 va_start (args, first_element);
1005 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
1010 /* Code copied from g_build_pathv(), and modifed to use two
1011 * alternative single-character separators.
1015 gboolean is_first = TRUE;
1016 gboolean have_leading = FALSE;
1017 const gchar *single_element = NULL;
1018 const gchar *next_element;
1019 const gchar *last_trailing = NULL;
1020 gchar current_separator = '\\';
1022 va_start (args, first_element);
1024 result = g_string_new (NULL);
1026 next_element = first_element;
1030 const gchar *element;
1036 element = next_element;
1037 next_element = va_arg (args, gchar *);
1042 /* Ignore empty elements */
1051 (*start == '\\' || *start == '/'))
1053 current_separator = *start;
1058 end = start + strlen (start);
1062 while (end >= start + 1 &&
1063 (end[-1] == '\\' || end[-1] == '/'))
1065 current_separator = end[-1];
1069 last_trailing = end;
1070 while (last_trailing >= element + 1 &&
1071 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1076 /* If the leading and trailing separator strings are in the
1077 * same element and overlap, the result is exactly that element
1079 if (last_trailing <= start)
1080 single_element = element;
1082 g_string_append_len (result, element, start - element);
1083 have_leading = TRUE;
1086 single_element = NULL;
1093 g_string_append_len (result, ¤t_separator, 1);
1095 g_string_append_len (result, start, end - start);
1103 g_string_free (result, TRUE);
1104 return g_strdup (single_element);
1109 g_string_append (result, last_trailing);
1111 return g_string_free (result, FALSE);
1118 * @filename: the symbolic link
1119 * @error: return location for a #GError
1121 * Reads the contents of the symbolic link @filename like the POSIX readlink() function.
1122 * The returned string is in the encoding used for filenames. Use g_filename_to_utf8() to
1123 * convert it to UTF-8.
1125 * Returns: A newly allocated string with the contents of the symbolic link,
1126 * or %NULL if an error occurred.
1131 g_file_read_link (const gchar *filename,
1134 #ifdef HAVE_READLINK
1140 buffer = g_malloc (size);
1144 read_size = readlink (filename, buffer, size);
1145 if (read_size < 0) {
1149 g_file_error_from_errno (errno),
1150 _("Failed to read the symbolic link '%s': %s"),
1151 filename, g_strerror (errno));
1156 if (read_size < size)
1158 buffer[read_size] = 0;
1163 buffer = g_realloc (buffer, size);
1169 _("Symbolic links not supported"));