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 */
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))
118 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
125 /* For root, on some POSIX systems, access (filename, X_OK)
126 * will succeed even if no executable bits are set on the
127 * file. We fall through to a stat test to avoid that.
131 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))
159 /* The extra test for root when access (file, X_OK) succeeds.
161 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
162 ((s.st_mode & S_IXOTH) ||
163 (s.st_mode & S_IXUSR) ||
164 (s.st_mode & S_IXGRP)))
174 g_file_error_quark (void)
178 q = g_quark_from_static_string ("g-file-error-quark");
184 * g_file_error_from_errno:
185 * @err_no: an "errno" value
187 * Gets a #GFileError constant based on the passed-in @errno.
188 * For example, if you pass in %EEXIST this function returns
189 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
190 * assume that all #GFileError values will exist.
192 * Normally a #GFileError value goes into a #GError returned
193 * from a function that manipulates files. So you would use
194 * g_file_error_from_errno() when constructing a #GError.
196 * Return value: #GFileError corresponding to the given @errno
199 g_file_error_from_errno (gint err_no)
205 return G_FILE_ERROR_EXIST;
211 return G_FILE_ERROR_ISDIR;
217 return G_FILE_ERROR_ACCES;
223 return G_FILE_ERROR_NAMETOOLONG;
229 return G_FILE_ERROR_NOENT;
235 return G_FILE_ERROR_NOTDIR;
241 return G_FILE_ERROR_NXIO;
247 return G_FILE_ERROR_NODEV;
253 return G_FILE_ERROR_ROFS;
259 return G_FILE_ERROR_TXTBSY;
265 return G_FILE_ERROR_FAULT;
271 return G_FILE_ERROR_LOOP;
277 return G_FILE_ERROR_NOSPC;
283 return G_FILE_ERROR_NOMEM;
289 return G_FILE_ERROR_MFILE;
295 return G_FILE_ERROR_NFILE;
301 return G_FILE_ERROR_BADF;
307 return G_FILE_ERROR_INVAL;
313 return G_FILE_ERROR_PIPE;
319 return G_FILE_ERROR_AGAIN;
325 return G_FILE_ERROR_INTR;
331 return G_FILE_ERROR_IO;
337 return G_FILE_ERROR_PERM;
342 return G_FILE_ERROR_FAILED;
348 get_contents_stdio (const gchar *filename,
358 size_t total_allocated;
360 g_assert (f != NULL);
362 #define STARTING_ALLOC 64
365 total_allocated = STARTING_ALLOC;
366 str = g_malloc (STARTING_ALLOC);
370 bytes = fread (buf, 1, 2048, f);
372 while ((total_bytes + bytes + 1) > total_allocated)
374 total_allocated *= 2;
375 str = g_try_realloc (str, total_allocated);
382 _("Could not allocate %lu bytes to read file \"%s\""),
383 (gulong) total_allocated, filename);
392 g_file_error_from_errno (errno),
393 _("Error reading file '%s': %s"),
394 filename, g_strerror (errno));
399 memcpy (str + total_bytes, buf, bytes);
400 total_bytes += bytes;
405 str[total_bytes] = '\0';
408 *length = total_bytes;
425 get_contents_regfile (const gchar *filename,
426 struct stat *stat_buf,
437 size = stat_buf->st_size;
439 alloc_size = size + 1;
440 buf = g_try_malloc (alloc_size);
447 _("Could not allocate %lu bytes to read file \"%s\""),
448 (gulong) alloc_size, filename);
454 while (bytes_read < size)
458 rc = read (fd, buf + bytes_read, size - bytes_read);
468 g_file_error_from_errno (errno),
469 _("Failed to read from file '%s': %s"),
470 filename, g_strerror (errno));
481 buf[bytes_read] = '\0';
484 *length = bytes_read;
500 get_contents_posix (const gchar *filename,
505 struct stat stat_buf;
508 /* O_BINARY useful on Cygwin */
509 fd = open (filename, O_RDONLY|O_BINARY);
515 g_file_error_from_errno (errno),
516 _("Failed to open file '%s': %s"),
517 filename, g_strerror (errno));
522 /* I don't think this will ever fail, aside from ENOMEM, but. */
523 if (fstat (fd, &stat_buf) < 0)
529 g_file_error_from_errno (errno),
530 _("Failed to get attributes of file '%s': fstat() failed: %s"),
531 filename, g_strerror (errno));
536 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
538 return get_contents_regfile (filename,
549 f = fdopen (fd, "r");
555 g_file_error_from_errno (errno),
556 _("Failed to open file '%s': fdopen() failed: %s"),
557 filename, g_strerror (errno));
562 return get_contents_stdio (filename, f, contents, length, error);
566 #else /* G_OS_WIN32 */
569 get_contents_win32 (const gchar *filename,
576 /* I guess you want binary mode; maybe you want text sometimes? */
577 f = fopen (filename, "rb");
583 g_file_error_from_errno (errno),
584 _("Failed to open file '%s': %s"),
585 filename, g_strerror (errno));
590 return get_contents_stdio (filename, f, contents, length, error);
596 * g_file_get_contents:
597 * @filename: a file to read contents from
598 * @contents: location to store an allocated string
599 * @length: location to store length in bytes of the contents
600 * @error: return location for a #GError
602 * Reads an entire file into allocated memory, with good error
603 * checking. If @error is set, %FALSE is returned, and @contents is set
604 * to %NULL. If %TRUE is returned, @error will not be set, and @contents
605 * will be set to the file contents. The string stored in @contents
606 * will be nul-terminated, so for text files you can pass %NULL for the
607 * @length argument. The error domain is #G_FILE_ERROR. Possible
608 * error codes are those in the #GFileError enumeration.
610 * Return value: %TRUE on success, %FALSE if error is set
613 g_file_get_contents (const gchar *filename,
618 g_return_val_if_fail (filename != NULL, FALSE);
619 g_return_val_if_fail (contents != NULL, FALSE);
626 return get_contents_win32 (filename, contents, length, error);
628 return get_contents_posix (filename, contents, length, error);
633 * mkstemp() implementation is from the GNU C library.
634 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
638 * @tmpl: template filename
640 * Opens a temporary file. See the <function>mkstemp()</function> documentation
641 * on most UNIX-like systems. This is a portability wrapper, which simply calls
642 * <function>mkstemp()</function> on systems that have it, and implements
643 * it in GLib otherwise.
645 * The parameter is a string that should match the rules for
646 * <function>mkstemp()</function>, i.e. end in "XXXXXX". The X string will
647 * be modified to form the name of a file that didn't exist.
649 * Return value: A file handle (as from <function>open()</function>) to the file
650 * opened for reading and writing. The file is opened in binary mode
651 * on platforms where there is a difference. The file handle should be
652 * closed with <function>close()</function>. In case of errors, -1 is returned.
655 g_mkstemp (char *tmpl)
658 return mkstemp (tmpl);
663 static const char letters[] =
664 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
665 static const int NLETTERS = sizeof (letters) - 1;
668 static int counter = 0;
671 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
674 /* This is where the Xs start. */
675 XXXXXX = &tmpl[len - 6];
677 /* Get some more or less random data. */
678 g_get_current_time (&tv);
679 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
681 for (count = 0; count < 100; value += 7777, ++count)
685 /* Fill in the random bits. */
686 XXXXXX[0] = letters[v % NLETTERS];
688 XXXXXX[1] = letters[v % NLETTERS];
690 XXXXXX[2] = letters[v % NLETTERS];
692 XXXXXX[3] = letters[v % NLETTERS];
694 XXXXXX[4] = letters[v % NLETTERS];
696 XXXXXX[5] = letters[v % NLETTERS];
698 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
702 else if (errno != EEXIST)
703 /* Any other error will apply also to other names we might
704 * try, and there are 2^32 or so of them, so give up now.
709 /* We got out of the loop because we ran out of combinations to try. */
716 * @tmpl: Template for file name, as in g_mkstemp(), basename only
717 * @name_used: location to store actual name used
718 * @error: return location for a #GError
720 * Opens a file for writing in the preferred directory for temporary
721 * files (as returned by g_get_tmp_dir()).
723 * @tmpl should be a string ending with six 'X' characters, as the
724 * parameter to g_mkstemp() (or <function>mkstemp()</function>).
725 * However, unlike these functions, the template should only be a
726 * basename, no directory components are allowed. If template is %NULL,
727 * a default template is used.
729 * Note that in contrast to g_mkstemp() (and <function>mkstemp()</function>)
730 * @tmpl is not modified, and might thus be a read-only literal string.
732 * The actual name used is returned in @name_used if non-%NULL. This
733 * string should be freed with g_free() when not needed any longer.
735 * Return value: A file handle (as from <function>open()</function>) to
736 * the file opened for reading and writing. The file is opened in binary
737 * mode on platforms where there is a difference. The file handle should be
738 * closed with <function>close()</function>. In case of errors, -1 is returned
739 * and @error will be set.
742 g_file_open_tmp (const char *tmpl,
754 if (strchr (tmpl, G_DIR_SEPARATOR)
756 || strchr (tmpl, '/')
763 _("Template '%s' invalid, should not contain a '%s'"),
764 tmpl, G_DIR_SEPARATOR_S);
769 if (strlen (tmpl) < 6 ||
770 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
775 _("Template '%s' doesn't end with XXXXXX"),
780 tmpdir = g_get_tmp_dir ();
782 if (tmpdir [strlen (tmpdir) - 1] == G_DIR_SEPARATOR)
785 sep = G_DIR_SEPARATOR_S;
787 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
789 retval = g_mkstemp (fulltemplate);
795 g_file_error_from_errno (errno),
796 _("Failed to create file '%s': %s"),
797 fulltemplate, g_strerror (errno));
798 g_free (fulltemplate);
803 *name_used = fulltemplate;
805 g_free (fulltemplate);
811 g_build_pathv (const gchar *separator,
812 const gchar *first_element,
816 gint separator_len = strlen (separator);
817 gboolean is_first = TRUE;
818 gboolean have_leading = FALSE;
819 const gchar *single_element = NULL;
820 const gchar *next_element;
821 const gchar *last_trailing = NULL;
823 result = g_string_new (NULL);
825 next_element = first_element;
829 const gchar *element;
835 element = next_element;
836 next_element = va_arg (args, gchar *);
841 /* Ignore empty elements */
850 strncmp (start, separator, separator_len) == 0)
851 start += separator_len;
854 end = start + strlen (start);
858 while (end >= start + separator_len &&
859 strncmp (end - separator_len, separator, separator_len) == 0)
860 end -= separator_len;
863 while (last_trailing >= element + separator_len &&
864 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
865 last_trailing -= separator_len;
869 /* If the leading and trailing separator strings are in the
870 * same element and overlap, the result is exactly that element
872 if (last_trailing <= start)
873 single_element = element;
875 g_string_append_len (result, element, start - element);
879 single_element = NULL;
886 g_string_append (result, separator);
888 g_string_append_len (result, start, end - start);
894 g_string_free (result, TRUE);
895 return g_strdup (single_element);
900 g_string_append (result, last_trailing);
902 return g_string_free (result, FALSE);
908 * @separator: a string used to separator the elements of the path.
909 * @first_element: the first element in the path
910 * @Varargs: remaining elements in path, terminated by %NULL
912 * Creates a path from a series of elements using @separator as the
913 * separator between elements. At the boundary between two elements,
914 * any trailing occurrences of separator in the first element, or
915 * leading occurrences of separator in the second element are removed
916 * and exactly one copy of the separator is inserted.
918 * Empty elements are ignored.
920 * The number of leading copies of the separator on the result is
921 * the same as the number of leading copies of the separator on
922 * the first non-empty element.
924 * The number of trailing copies of the separator on the result is
925 * the same as the number of trailing copies of the separator on
926 * the last non-empty element. (Determination of the number of
927 * trailing copies is done without stripping leading copies, so
928 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
929 * has 1 trailing copy.)
931 * However, if there is only a single non-empty element, and there
932 * are no characters in that element not part of the leading or
933 * trailing separators, then the result is exactly the original value
936 * Other than for determination of the number of leading and trailing
937 * copies of the separator, elements consisting only of copies
938 * of the separator are ignored.
940 * Return value: a newly-allocated string that must be freed with g_free().
943 g_build_path (const gchar *separator,
944 const gchar *first_element,
950 g_return_val_if_fail (separator != NULL, NULL);
952 va_start (args, first_element);
953 str = g_build_pathv (separator, first_element, args);
961 * @first_element: the first element in the path
962 * @Varargs: remaining elements in path, terminated by %NULL
964 * Creates a filename from a series of elements using the correct
965 * separator for filenames. This function behaves identically
966 * to <literal>g_build_path (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
968 * No attempt is made to force the resulting filename to be an absolute
969 * path. If the first element is a relative path, the result will
970 * be a relative path.
972 * Return value: a newly-allocated string that must be freed with g_free().
975 g_build_filename (const gchar *first_element,
981 va_start (args, first_element);
982 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);