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 */
70 * @filename: a filename to test
71 * @test: bitfield of #GFileTest flags
73 * Returns %TRUE if any of the tests in the bitfield @test are
74 * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS |
75 * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists;
76 * the check whether it's a directory doesn't matter since the existence
77 * test is %TRUE. With the current set of available tests, there's no point
78 * passing in more than one test at a time.
80 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
81 * so for a symbolic link to a regular file g_file_test() will return
82 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
84 * Note, that for a dangling symbolic link g_file_test() will return
85 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
87 * You should never use g_file_test() to test whether it is safe
88 * to perform an operaton, because there is always the possibility
89 * of the condition changing before you actually perform the operation.
90 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
91 * to know whether it is is safe to write to a file without being
92 * tricked into writing into a different location. It doesn't work!
94 * <informalexample><programlisting>
95 * /* DON'T DO THIS */
96 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) {
97 * fd = open (filename, O_WRONLY);
98 * /* write to fd */
100 * </programlisting></informalexample>
102 * Another thing to note is that %G_FILE_TEST_EXISTS and
103 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
104 * system call. This usually doesn't matter, but if your program
105 * is setuid or setgid it means that these tests will give you
106 * the answer for the real user ID and group ID , rather than the
107 * effective user ID and group ID.
109 * Return value: whether a test was %TRUE
112 g_file_test (const gchar *filename,
115 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
119 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
124 /* For root, on some POSIX systems, access (filename, X_OK)
125 * will succeed even if no executable bits are set on the
126 * file. We fall through to a stat test to avoid that.
130 test &= ~G_FILE_TEST_IS_EXECUTABLE;
133 if (test & G_FILE_TEST_IS_SYMLINK)
136 /* no sym links on win32, no lstat in msvcrt */
140 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
145 if (test & (G_FILE_TEST_IS_REGULAR |
147 G_FILE_TEST_IS_EXECUTABLE))
151 if (stat (filename, &s) == 0)
153 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
156 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
160 /* The extra test for root when access (file, X_OK) succeeds.
161 * Probably only makes sense on Unix.
163 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
164 ((s.st_mode & S_IXOTH) ||
165 (s.st_mode & S_IXUSR) ||
166 (s.st_mode & S_IXGRP)))
169 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
170 (s.st_mode & _S_IEXEC))
180 g_file_error_quark (void)
184 q = g_quark_from_static_string ("g-file-error-quark");
190 * g_file_error_from_errno:
191 * @err_no: an "errno" value
193 * Gets a #GFileError constant based on the passed-in @errno.
194 * For example, if you pass in %EEXIST this function returns
195 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
196 * assume that all #GFileError values will exist.
198 * Normally a #GFileError value goes into a #GError returned
199 * from a function that manipulates files. So you would use
200 * g_file_error_from_errno() when constructing a #GError.
202 * Return value: #GFileError corresponding to the given @errno
205 g_file_error_from_errno (gint err_no)
211 return G_FILE_ERROR_EXIST;
217 return G_FILE_ERROR_ISDIR;
223 return G_FILE_ERROR_ACCES;
229 return G_FILE_ERROR_NAMETOOLONG;
235 return G_FILE_ERROR_NOENT;
241 return G_FILE_ERROR_NOTDIR;
247 return G_FILE_ERROR_NXIO;
253 return G_FILE_ERROR_NODEV;
259 return G_FILE_ERROR_ROFS;
265 return G_FILE_ERROR_TXTBSY;
271 return G_FILE_ERROR_FAULT;
277 return G_FILE_ERROR_LOOP;
283 return G_FILE_ERROR_NOSPC;
289 return G_FILE_ERROR_NOMEM;
295 return G_FILE_ERROR_MFILE;
301 return G_FILE_ERROR_NFILE;
307 return G_FILE_ERROR_BADF;
313 return G_FILE_ERROR_INVAL;
319 return G_FILE_ERROR_PIPE;
325 return G_FILE_ERROR_AGAIN;
331 return G_FILE_ERROR_INTR;
337 return G_FILE_ERROR_IO;
343 return G_FILE_ERROR_PERM;
349 return G_FILE_ERROR_NOSYS;
354 return G_FILE_ERROR_FAILED;
360 get_contents_stdio (const gchar *filename,
370 size_t total_allocated;
372 g_assert (f != NULL);
374 #define STARTING_ALLOC 64
377 total_allocated = STARTING_ALLOC;
378 str = g_malloc (STARTING_ALLOC);
382 bytes = fread (buf, 1, 2048, f);
384 while ((total_bytes + bytes + 1) > total_allocated)
386 total_allocated *= 2;
387 str = g_try_realloc (str, total_allocated);
391 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
396 _("Could not allocate %lu bytes to read file \"%s\""),
397 (gulong) total_allocated,
398 utf8_filename ? utf8_filename : "???");
399 g_free (utf8_filename);
407 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
411 g_file_error_from_errno (errno),
412 _("Error reading file '%s': %s"),
413 utf8_filename ? utf8_filename : "???",
415 g_free (utf8_filename);
420 memcpy (str + total_bytes, buf, bytes);
421 total_bytes += bytes;
426 str[total_bytes] = '\0';
429 *length = total_bytes;
446 get_contents_regfile (const gchar *filename,
447 struct stat *stat_buf,
458 size = stat_buf->st_size;
460 alloc_size = size + 1;
461 buf = g_try_malloc (alloc_size);
465 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
470 _("Could not allocate %lu bytes to read file \"%s\""),
472 utf8_filename ? utf8_filename : "???");
473 g_free (utf8_filename);
479 while (bytes_read < size)
483 rc = read (fd, buf + bytes_read, size - bytes_read);
489 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
494 g_file_error_from_errno (errno),
495 _("Failed to read from file '%s': %s"),
496 utf8_filename ? utf8_filename : "???",
498 g_free (utf8_filename);
509 buf[bytes_read] = '\0';
512 *length = bytes_read;
528 get_contents_posix (const gchar *filename,
533 struct stat stat_buf;
536 /* O_BINARY useful on Cygwin */
537 fd = open (filename, O_RDONLY|O_BINARY);
541 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
545 g_file_error_from_errno (errno),
546 _("Failed to open file '%s': %s"),
547 utf8_filename ? utf8_filename : "???",
549 g_free (utf8_filename);
554 /* I don't think this will ever fail, aside from ENOMEM, but. */
555 if (fstat (fd, &stat_buf) < 0)
557 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
562 g_file_error_from_errno (errno),
563 _("Failed to get attributes of file '%s': fstat() failed: %s"),
564 utf8_filename ? utf8_filename : "???",
566 g_free (utf8_filename);
571 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
573 return get_contents_regfile (filename,
584 f = fdopen (fd, "r");
588 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
593 g_file_error_from_errno (errno),
594 _("Failed to open file '%s': fdopen() failed: %s"),
595 utf8_filename ? utf8_filename : "???",
597 g_free (utf8_filename);
602 return get_contents_stdio (filename, f, contents, length, error);
606 #else /* G_OS_WIN32 */
609 get_contents_win32 (const gchar *filename,
616 /* I guess you want binary mode; maybe you want text sometimes? */
617 f = fopen (filename, "rb");
621 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
626 g_file_error_from_errno (errno),
627 _("Failed to open file '%s': %s"),
628 utf8_filename ? utf8_filename : "???",
630 g_free (utf8_filename);
635 return get_contents_stdio (filename, f, contents, length, error);
641 * g_file_get_contents:
642 * @filename: a file to read contents from
643 * @contents: location to store an allocated string
644 * @length: location to store length in bytes of the contents
645 * @error: return location for a #GError
647 * Reads an entire file into allocated memory, with good error
648 * checking. If @error is set, %FALSE is returned, and @contents is set
649 * to %NULL. If %TRUE is returned, @error will not be set, and @contents
650 * will be set to the file contents. The string stored in @contents
651 * will be nul-terminated, so for text files you can pass %NULL for the
652 * @length argument. The error domain is #G_FILE_ERROR. Possible
653 * error codes are those in the #GFileError enumeration.
655 * Return value: %TRUE on success, %FALSE if error is set
658 g_file_get_contents (const gchar *filename,
663 g_return_val_if_fail (filename != NULL, FALSE);
664 g_return_val_if_fail (contents != NULL, FALSE);
671 return get_contents_win32 (filename, contents, length, error);
673 return get_contents_posix (filename, contents, length, error);
678 * mkstemp() implementation is from the GNU C library.
679 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
683 * @tmpl: template filename
685 * Opens a temporary file. See the mkstemp() documentation
686 * on most UNIX-like systems. This is a portability wrapper, which simply calls
687 * mkstemp() on systems that have it, and implements
688 * it in GLib otherwise.
690 * The parameter is a string that should match the rules for
691 * mkstemp(), i.e. end in "XXXXXX". The X string will
692 * be modified to form the name of a file that didn't exist.
694 * Return value: A file handle (as from open()) to the file
695 * opened for reading and writing. The file is opened in binary mode
696 * on platforms where there is a difference. The file handle should be
697 * closed with close(). In case of errors, -1 is returned.
700 g_mkstemp (gchar *tmpl)
703 return mkstemp (tmpl);
708 static const char letters[] =
709 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
710 static const int NLETTERS = sizeof (letters) - 1;
713 static int counter = 0;
716 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
719 /* This is where the Xs start. */
720 XXXXXX = &tmpl[len - 6];
722 /* Get some more or less random data. */
723 g_get_current_time (&tv);
724 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
726 for (count = 0; count < 100; value += 7777, ++count)
730 /* Fill in the random bits. */
731 XXXXXX[0] = letters[v % NLETTERS];
733 XXXXXX[1] = letters[v % NLETTERS];
735 XXXXXX[2] = letters[v % NLETTERS];
737 XXXXXX[3] = letters[v % NLETTERS];
739 XXXXXX[4] = letters[v % NLETTERS];
741 XXXXXX[5] = letters[v % NLETTERS];
743 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
747 else if (errno != EEXIST)
748 /* Any other error will apply also to other names we might
749 * try, and there are 2^32 or so of them, so give up now.
754 /* We got out of the loop because we ran out of combinations to try. */
761 * @tmpl: Template for file name, as in g_mkstemp(), basename only
762 * @name_used: location to store actual name used
763 * @error: return location for a #GError
765 * Opens a file for writing in the preferred directory for temporary
766 * files (as returned by g_get_tmp_dir()).
768 * @tmpl should be a string ending with six 'X' characters, as the
769 * parameter to g_mkstemp() (or mkstemp()).
770 * However, unlike these functions, the template should only be a
771 * basename, no directory components are allowed. If template is %NULL,
772 * a default template is used.
774 * Note that in contrast to g_mkstemp() (and mkstemp())
775 * @tmpl is not modified, and might thus be a read-only literal string.
777 * The actual name used is returned in @name_used if non-%NULL. This
778 * string should be freed with g_free() when not needed any longer.
780 * Return value: A file handle (as from open()) to
781 * the file opened for reading and writing. The file is opened in binary
782 * mode on platforms where there is a difference. The file handle should be
783 * closed with close(). In case of errors, -1 is returned
784 * and @error will be set.
787 g_file_open_tmp (const gchar *tmpl,
800 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
802 || (strchr (tmpl, '/') != NULL && (slash = "/"))
813 _("Template '%s' invalid, should not contain a '%s'"),
819 if (strlen (tmpl) < 6 ||
820 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
825 _("Template '%s' doesn't end with XXXXXX"),
830 tmpdir = g_get_tmp_dir ();
832 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
835 sep = G_DIR_SEPARATOR_S;
837 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
839 retval = g_mkstemp (fulltemplate);
845 g_file_error_from_errno (errno),
846 _("Failed to create file '%s': %s"),
847 fulltemplate, g_strerror (errno));
848 g_free (fulltemplate);
853 *name_used = fulltemplate;
855 g_free (fulltemplate);
861 g_build_pathv (const gchar *separator,
862 const gchar *first_element,
866 gint separator_len = strlen (separator);
867 gboolean is_first = TRUE;
868 gboolean have_leading = FALSE;
869 const gchar *single_element = NULL;
870 const gchar *next_element;
871 const gchar *last_trailing = NULL;
873 result = g_string_new (NULL);
875 next_element = first_element;
879 const gchar *element;
885 element = next_element;
886 next_element = va_arg (args, gchar *);
891 /* Ignore empty elements */
900 strncmp (start, separator, separator_len) == 0)
901 start += separator_len;
904 end = start + strlen (start);
908 while (end >= start + separator_len &&
909 strncmp (end - separator_len, separator, separator_len) == 0)
910 end -= separator_len;
913 while (last_trailing >= element + separator_len &&
914 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
915 last_trailing -= separator_len;
919 /* If the leading and trailing separator strings are in the
920 * same element and overlap, the result is exactly that element
922 if (last_trailing <= start)
923 single_element = element;
925 g_string_append_len (result, element, start - element);
929 single_element = NULL;
936 g_string_append (result, separator);
938 g_string_append_len (result, start, end - start);
944 g_string_free (result, TRUE);
945 return g_strdup (single_element);
950 g_string_append (result, last_trailing);
952 return g_string_free (result, FALSE);
958 * @separator: a string used to separator the elements of the path.
959 * @first_element: the first element in the path
960 * @Varargs: remaining elements in path, terminated by %NULL
962 * Creates a path from a series of elements using @separator as the
963 * separator between elements. At the boundary between two elements,
964 * any trailing occurrences of separator in the first element, or
965 * leading occurrences of separator in the second element are removed
966 * and exactly one copy of the separator is inserted.
968 * Empty elements are ignored.
970 * The number of leading copies of the separator on the result is
971 * the same as the number of leading copies of the separator on
972 * the first non-empty element.
974 * The number of trailing copies of the separator on the result is
975 * the same as the number of trailing copies of the separator on
976 * the last non-empty element. (Determination of the number of
977 * trailing copies is done without stripping leading copies, so
978 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
979 * has 1 trailing copy.)
981 * However, if there is only a single non-empty element, and there
982 * are no characters in that element not part of the leading or
983 * trailing separators, then the result is exactly the original value
986 * Other than for determination of the number of leading and trailing
987 * copies of the separator, elements consisting only of copies
988 * of the separator are ignored.
990 * Return value: a newly-allocated string that must be freed with g_free().
993 g_build_path (const gchar *separator,
994 const gchar *first_element,
1000 g_return_val_if_fail (separator != NULL, NULL);
1002 va_start (args, first_element);
1003 str = g_build_pathv (separator, first_element, args);
1011 * @first_element: the first element in the path
1012 * @Varargs: remaining elements in path, terminated by %NULL
1014 * Creates a filename from a series of elements using the correct
1015 * separator for filenames.
1017 * On Unix, this function behaves identically to <literal>g_build_path
1018 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1020 * On Windows, it takes into account that either the backslash
1021 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1022 * as separator in filenames, but otherwise behaves as on Unix. When
1023 * file pathname separators need to be inserted, the one that last
1024 * previously occurred in the parameters (reading from left to right)
1027 * No attempt is made to force the resulting filename to be an absolute
1028 * path. If the first element is a relative path, the result will
1029 * be a relative path.
1031 * Return value: a newly-allocated string that must be freed with g_free().
1034 g_build_filename (const gchar *first_element,
1041 va_start (args, first_element);
1042 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
1047 /* Code copied from g_build_pathv(), and modifed to use two
1048 * alternative single-character separators.
1052 gboolean is_first = TRUE;
1053 gboolean have_leading = FALSE;
1054 const gchar *single_element = NULL;
1055 const gchar *next_element;
1056 const gchar *last_trailing = NULL;
1057 gchar current_separator = '\\';
1059 va_start (args, first_element);
1061 result = g_string_new (NULL);
1063 next_element = first_element;
1067 const gchar *element;
1073 element = next_element;
1074 next_element = va_arg (args, gchar *);
1079 /* Ignore empty elements */
1088 (*start == '\\' || *start == '/'))
1090 current_separator = *start;
1095 end = start + strlen (start);
1099 while (end >= start + 1 &&
1100 (end[-1] == '\\' || end[-1] == '/'))
1102 current_separator = end[-1];
1106 last_trailing = end;
1107 while (last_trailing >= element + 1 &&
1108 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1113 /* If the leading and trailing separator strings are in the
1114 * same element and overlap, the result is exactly that element
1116 if (last_trailing <= start)
1117 single_element = element;
1119 g_string_append_len (result, element, start - element);
1120 have_leading = TRUE;
1123 single_element = NULL;
1130 g_string_append_len (result, ¤t_separator, 1);
1132 g_string_append_len (result, start, end - start);
1140 g_string_free (result, TRUE);
1141 return g_strdup (single_element);
1146 g_string_append (result, last_trailing);
1148 return g_string_free (result, FALSE);
1155 * @filename: the symbolic link
1156 * @error: return location for a #GError
1158 * Reads the contents of the symbolic link @filename like the POSIX readlink() function.
1159 * The returned string is in the encoding used for filenames. Use g_filename_to_utf8() to
1160 * convert it to UTF-8.
1162 * Returns: A newly allocated string with the contents of the symbolic link,
1163 * or %NULL if an error occurred.
1168 g_file_read_link (const gchar *filename,
1171 #ifdef HAVE_READLINK
1177 buffer = g_malloc (size);
1181 read_size = readlink (filename, buffer, size);
1182 if (read_size < 0) {
1183 gchar *utf8_filename = g_filename_to_utf8 (filename, -1,
1188 g_file_error_from_errno (errno),
1189 _("Failed to read the symbolic link '%s': %s"),
1190 utf8_filename ? utf8_filename : "???",
1191 g_strerror (errno));
1192 g_free (utf8_filename);
1197 if (read_size < size)
1199 buffer[read_size] = 0;
1204 buffer = g_realloc (buffer, size);
1210 _("Symbolic links not supported"));