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;
354 return G_FILE_ERROR_NOSYS;
359 return G_FILE_ERROR_FAILED;
365 get_contents_stdio (const gchar *filename,
375 size_t total_allocated;
377 g_assert (f != NULL);
379 #define STARTING_ALLOC 64
382 total_allocated = STARTING_ALLOC;
383 str = g_malloc (STARTING_ALLOC);
387 bytes = fread (buf, 1, 2048, f);
389 while ((total_bytes + bytes + 1) > total_allocated)
391 total_allocated *= 2;
392 str = g_try_realloc (str, total_allocated);
399 _("Could not allocate %lu bytes to read file \"%s\""),
400 (gulong) total_allocated, filename);
409 g_file_error_from_errno (errno),
410 _("Error reading file '%s': %s"),
411 filename, g_strerror (errno));
416 memcpy (str + total_bytes, buf, bytes);
417 total_bytes += bytes;
422 str[total_bytes] = '\0';
425 *length = total_bytes;
442 get_contents_regfile (const gchar *filename,
443 struct stat *stat_buf,
454 size = stat_buf->st_size;
456 alloc_size = size + 1;
457 buf = g_try_malloc (alloc_size);
464 _("Could not allocate %lu bytes to read file \"%s\""),
465 (gulong) alloc_size, filename);
471 while (bytes_read < size)
475 rc = read (fd, buf + bytes_read, size - bytes_read);
485 g_file_error_from_errno (errno),
486 _("Failed to read from file '%s': %s"),
487 filename, g_strerror (errno));
498 buf[bytes_read] = '\0';
501 *length = bytes_read;
517 get_contents_posix (const gchar *filename,
522 struct stat stat_buf;
525 /* O_BINARY useful on Cygwin */
526 fd = open (filename, O_RDONLY|O_BINARY);
532 g_file_error_from_errno (errno),
533 _("Failed to open file '%s': %s"),
534 filename, g_strerror (errno));
539 /* I don't think this will ever fail, aside from ENOMEM, but. */
540 if (fstat (fd, &stat_buf) < 0)
546 g_file_error_from_errno (errno),
547 _("Failed to get attributes of file '%s': fstat() failed: %s"),
548 filename, g_strerror (errno));
553 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
555 return get_contents_regfile (filename,
566 f = fdopen (fd, "r");
572 g_file_error_from_errno (errno),
573 _("Failed to open file '%s': fdopen() failed: %s"),
574 filename, g_strerror (errno));
579 return get_contents_stdio (filename, f, contents, length, error);
583 #else /* G_OS_WIN32 */
586 get_contents_win32 (const gchar *filename,
593 /* I guess you want binary mode; maybe you want text sometimes? */
594 f = fopen (filename, "rb");
600 g_file_error_from_errno (errno),
601 _("Failed to open file '%s': %s"),
602 filename, g_strerror (errno));
607 return get_contents_stdio (filename, f, contents, length, error);
613 * g_file_get_contents:
614 * @filename: a file to read contents from
615 * @contents: location to store an allocated string
616 * @length: location to store length in bytes of the contents
617 * @error: return location for a #GError
619 * Reads an entire file into allocated memory, with good error
620 * checking. If @error is set, %FALSE is returned, and @contents is set
621 * to %NULL. If %TRUE is returned, @error will not be set, and @contents
622 * will be set to the file contents. The string stored in @contents
623 * will be nul-terminated, so for text files you can pass %NULL for the
624 * @length argument. The error domain is #G_FILE_ERROR. Possible
625 * error codes are those in the #GFileError enumeration.
627 * Return value: %TRUE on success, %FALSE if error is set
630 g_file_get_contents (const gchar *filename,
635 g_return_val_if_fail (filename != NULL, FALSE);
636 g_return_val_if_fail (contents != NULL, FALSE);
643 return get_contents_win32 (filename, contents, length, error);
645 return get_contents_posix (filename, contents, length, error);
650 * mkstemp() implementation is from the GNU C library.
651 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
655 * @tmpl: template filename
657 * Opens a temporary file. See the mkstemp() documentation
658 * on most UNIX-like systems. This is a portability wrapper, which simply calls
659 * mkstemp() on systems that have it, and implements
660 * it in GLib otherwise.
662 * The parameter is a string that should match the rules for
663 * mkstemp(), i.e. end in "XXXXXX". The X string will
664 * be modified to form the name of a file that didn't exist.
666 * Return value: A file handle (as from open()) to the file
667 * opened for reading and writing. The file is opened in binary mode
668 * on platforms where there is a difference. The file handle should be
669 * closed with close(). In case of errors, -1 is returned.
672 g_mkstemp (gchar *tmpl)
675 return mkstemp (tmpl);
680 static const char letters[] =
681 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
682 static const int NLETTERS = sizeof (letters) - 1;
685 static int counter = 0;
688 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
691 /* This is where the Xs start. */
692 XXXXXX = &tmpl[len - 6];
694 /* Get some more or less random data. */
695 g_get_current_time (&tv);
696 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
698 for (count = 0; count < 100; value += 7777, ++count)
702 /* Fill in the random bits. */
703 XXXXXX[0] = letters[v % NLETTERS];
705 XXXXXX[1] = letters[v % NLETTERS];
707 XXXXXX[2] = letters[v % NLETTERS];
709 XXXXXX[3] = letters[v % NLETTERS];
711 XXXXXX[4] = letters[v % NLETTERS];
713 XXXXXX[5] = letters[v % NLETTERS];
715 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
719 else if (errno != EEXIST)
720 /* Any other error will apply also to other names we might
721 * try, and there are 2^32 or so of them, so give up now.
726 /* We got out of the loop because we ran out of combinations to try. */
733 * @tmpl: Template for file name, as in g_mkstemp(), basename only
734 * @name_used: location to store actual name used
735 * @error: return location for a #GError
737 * Opens a file for writing in the preferred directory for temporary
738 * files (as returned by g_get_tmp_dir()).
740 * @tmpl should be a string ending with six 'X' characters, as the
741 * parameter to g_mkstemp() (or mkstemp()).
742 * However, unlike these functions, the template should only be a
743 * basename, no directory components are allowed. If template is %NULL,
744 * a default template is used.
746 * Note that in contrast to g_mkstemp() (and mkstemp())
747 * @tmpl is not modified, and might thus be a read-only literal string.
749 * The actual name used is returned in @name_used if non-%NULL. This
750 * string should be freed with g_free() when not needed any longer.
752 * Return value: A file handle (as from open()) to
753 * the file opened for reading and writing. The file is opened in binary
754 * mode on platforms where there is a difference. The file handle should be
755 * closed with close(). In case of errors, -1 is returned
756 * and @error will be set.
759 g_file_open_tmp (const gchar *tmpl,
772 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
774 || (strchr (tmpl, '/') != NULL && (slash = "/"))
785 _("Template '%s' invalid, should not contain a '%s'"),
791 if (strlen (tmpl) < 6 ||
792 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
797 _("Template '%s' doesn't end with XXXXXX"),
802 tmpdir = g_get_tmp_dir ();
804 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
807 sep = G_DIR_SEPARATOR_S;
809 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
811 retval = g_mkstemp (fulltemplate);
817 g_file_error_from_errno (errno),
818 _("Failed to create file '%s': %s"),
819 fulltemplate, g_strerror (errno));
820 g_free (fulltemplate);
825 *name_used = fulltemplate;
827 g_free (fulltemplate);
833 g_build_pathv (const gchar *separator,
834 const gchar *first_element,
838 gint separator_len = strlen (separator);
839 gboolean is_first = TRUE;
840 gboolean have_leading = FALSE;
841 const gchar *single_element = NULL;
842 const gchar *next_element;
843 const gchar *last_trailing = NULL;
845 result = g_string_new (NULL);
847 next_element = first_element;
851 const gchar *element;
857 element = next_element;
858 next_element = va_arg (args, gchar *);
863 /* Ignore empty elements */
872 strncmp (start, separator, separator_len) == 0)
873 start += separator_len;
876 end = start + strlen (start);
880 while (end >= start + separator_len &&
881 strncmp (end - separator_len, separator, separator_len) == 0)
882 end -= separator_len;
885 while (last_trailing >= element + separator_len &&
886 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
887 last_trailing -= separator_len;
891 /* If the leading and trailing separator strings are in the
892 * same element and overlap, the result is exactly that element
894 if (last_trailing <= start)
895 single_element = element;
897 g_string_append_len (result, element, start - element);
901 single_element = NULL;
908 g_string_append (result, separator);
910 g_string_append_len (result, start, end - start);
916 g_string_free (result, TRUE);
917 return g_strdup (single_element);
922 g_string_append (result, last_trailing);
924 return g_string_free (result, FALSE);
930 * @separator: a string used to separator the elements of the path.
931 * @first_element: the first element in the path
932 * @Varargs: remaining elements in path, terminated by %NULL
934 * Creates a path from a series of elements using @separator as the
935 * separator between elements. At the boundary between two elements,
936 * any trailing occurrences of separator in the first element, or
937 * leading occurrences of separator in the second element are removed
938 * and exactly one copy of the separator is inserted.
940 * Empty elements are ignored.
942 * The number of leading copies of the separator on the result is
943 * the same as the number of leading copies of the separator on
944 * the first non-empty element.
946 * The number of trailing copies of the separator on the result is
947 * the same as the number of trailing copies of the separator on
948 * the last non-empty element. (Determination of the number of
949 * trailing copies is done without stripping leading copies, so
950 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
951 * has 1 trailing copy.)
953 * However, if there is only a single non-empty element, and there
954 * are no characters in that element not part of the leading or
955 * trailing separators, then the result is exactly the original value
958 * Other than for determination of the number of leading and trailing
959 * copies of the separator, elements consisting only of copies
960 * of the separator are ignored.
962 * Return value: a newly-allocated string that must be freed with g_free().
965 g_build_path (const gchar *separator,
966 const gchar *first_element,
972 g_return_val_if_fail (separator != NULL, NULL);
974 va_start (args, first_element);
975 str = g_build_pathv (separator, first_element, args);
983 * @first_element: the first element in the path
984 * @Varargs: remaining elements in path, terminated by %NULL
986 * Creates a filename from a series of elements using the correct
987 * separator for filenames.
989 * On Unix, this function behaves identically to <literal>g_build_path
990 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
992 * On Windows, it takes into account that either the backslash
993 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
994 * as separator in filenames, but otherwise behaves as on Unix. When
995 * file pathname separators need to be inserted, the one that last
996 * previously occurred in the parameters (reading from left to right)
999 * No attempt is made to force the resulting filename to be an absolute
1000 * path. If the first element is a relative path, the result will
1001 * be a relative path.
1003 * Return value: a newly-allocated string that must be freed with g_free().
1006 g_build_filename (const gchar *first_element,
1013 va_start (args, first_element);
1014 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
1019 /* Code copied from g_build_pathv(), and modifed to use two
1020 * alternative single-character separators.
1024 gboolean is_first = TRUE;
1025 gboolean have_leading = FALSE;
1026 const gchar *single_element = NULL;
1027 const gchar *next_element;
1028 const gchar *last_trailing = NULL;
1029 gchar current_separator = '\\';
1031 va_start (args, first_element);
1033 result = g_string_new (NULL);
1035 next_element = first_element;
1039 const gchar *element;
1045 element = next_element;
1046 next_element = va_arg (args, gchar *);
1051 /* Ignore empty elements */
1060 (*start == '\\' || *start == '/'))
1062 current_separator = *start;
1067 end = start + strlen (start);
1071 while (end >= start + 1 &&
1072 (end[-1] == '\\' || end[-1] == '/'))
1074 current_separator = end[-1];
1078 last_trailing = end;
1079 while (last_trailing >= element + 1 &&
1080 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1085 /* If the leading and trailing separator strings are in the
1086 * same element and overlap, the result is exactly that element
1088 if (last_trailing <= start)
1089 single_element = element;
1091 g_string_append_len (result, element, start - element);
1092 have_leading = TRUE;
1095 single_element = NULL;
1102 g_string_append_len (result, ¤t_separator, 1);
1104 g_string_append_len (result, start, end - start);
1112 g_string_free (result, TRUE);
1113 return g_strdup (single_element);
1118 g_string_append (result, last_trailing);
1120 return g_string_free (result, FALSE);
1127 * @filename: the symbolic link
1128 * @error: return location for a #GError
1130 * Reads the contents of the symbolic link @filename like the POSIX readlink() function.
1131 * The returned string is in the encoding used for filenames. Use g_filename_to_utf8() to
1132 * convert it to UTF-8.
1134 * Returns: A newly allocated string with the contents of the symbolic link,
1135 * or %NULL if an error occurred.
1140 g_file_read_link (const gchar *filename,
1143 #ifdef HAVE_READLINK
1149 buffer = g_malloc (size);
1153 read_size = readlink (filename, buffer, size);
1154 if (read_size < 0) {
1158 g_file_error_from_errno (errno),
1159 _("Failed to read the symbolic link '%s': %s"),
1160 filename, g_strerror (errno));
1165 if (read_size < size)
1167 buffer[read_size] = 0;
1172 buffer = g_realloc (buffer, size);
1178 _("Symbolic links not supported"));