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))
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)))
176 g_file_error_quark (void)
180 q = g_quark_from_static_string ("g-file-error-quark");
186 * g_file_error_from_errno:
187 * @err_no: an "errno" value
189 * Gets a #GFileError constant based on the passed-in @errno.
190 * For example, if you pass in %EEXIST this function returns
191 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
192 * assume that all #GFileError values will exist.
194 * Normally a #GFileError value goes into a #GError returned
195 * from a function that manipulates files. So you would use
196 * g_file_error_from_errno() when constructing a #GError.
198 * Return value: #GFileError corresponding to the given @errno
201 g_file_error_from_errno (gint err_no)
207 return G_FILE_ERROR_EXIST;
213 return G_FILE_ERROR_ISDIR;
219 return G_FILE_ERROR_ACCES;
225 return G_FILE_ERROR_NAMETOOLONG;
231 return G_FILE_ERROR_NOENT;
237 return G_FILE_ERROR_NOTDIR;
243 return G_FILE_ERROR_NXIO;
249 return G_FILE_ERROR_NODEV;
255 return G_FILE_ERROR_ROFS;
261 return G_FILE_ERROR_TXTBSY;
267 return G_FILE_ERROR_FAULT;
273 return G_FILE_ERROR_LOOP;
279 return G_FILE_ERROR_NOSPC;
285 return G_FILE_ERROR_NOMEM;
291 return G_FILE_ERROR_MFILE;
297 return G_FILE_ERROR_NFILE;
303 return G_FILE_ERROR_BADF;
309 return G_FILE_ERROR_INVAL;
315 return G_FILE_ERROR_PIPE;
321 return G_FILE_ERROR_AGAIN;
327 return G_FILE_ERROR_INTR;
333 return G_FILE_ERROR_IO;
339 return G_FILE_ERROR_PERM;
344 return G_FILE_ERROR_FAILED;
350 get_contents_stdio (const gchar *filename,
360 size_t total_allocated;
362 g_assert (f != NULL);
364 #define STARTING_ALLOC 64
367 total_allocated = STARTING_ALLOC;
368 str = g_malloc (STARTING_ALLOC);
372 bytes = fread (buf, 1, 2048, f);
374 while ((total_bytes + bytes + 1) > total_allocated)
376 total_allocated *= 2;
377 str = g_try_realloc (str, total_allocated);
384 _("Could not allocate %lu bytes to read file \"%s\""),
385 (gulong) total_allocated, filename);
394 g_file_error_from_errno (errno),
395 _("Error reading file '%s': %s"),
396 filename, g_strerror (errno));
401 memcpy (str + total_bytes, buf, bytes);
402 total_bytes += bytes;
407 str[total_bytes] = '\0';
410 *length = total_bytes;
427 get_contents_regfile (const gchar *filename,
428 struct stat *stat_buf,
439 size = stat_buf->st_size;
441 alloc_size = size + 1;
442 buf = g_try_malloc (alloc_size);
449 _("Could not allocate %lu bytes to read file \"%s\""),
450 (gulong) alloc_size, filename);
456 while (bytes_read < size)
460 rc = read (fd, buf + bytes_read, size - bytes_read);
470 g_file_error_from_errno (errno),
471 _("Failed to read from file '%s': %s"),
472 filename, g_strerror (errno));
483 buf[bytes_read] = '\0';
486 *length = bytes_read;
502 get_contents_posix (const gchar *filename,
507 struct stat stat_buf;
510 /* O_BINARY useful on Cygwin */
511 fd = open (filename, O_RDONLY|O_BINARY);
517 g_file_error_from_errno (errno),
518 _("Failed to open file '%s': %s"),
519 filename, g_strerror (errno));
524 /* I don't think this will ever fail, aside from ENOMEM, but. */
525 if (fstat (fd, &stat_buf) < 0)
531 g_file_error_from_errno (errno),
532 _("Failed to get attributes of file '%s': fstat() failed: %s"),
533 filename, g_strerror (errno));
538 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
540 return get_contents_regfile (filename,
551 f = fdopen (fd, "r");
557 g_file_error_from_errno (errno),
558 _("Failed to open file '%s': fdopen() failed: %s"),
559 filename, g_strerror (errno));
564 return get_contents_stdio (filename, f, contents, length, error);
568 #else /* G_OS_WIN32 */
571 get_contents_win32 (const gchar *filename,
578 /* I guess you want binary mode; maybe you want text sometimes? */
579 f = fopen (filename, "rb");
585 g_file_error_from_errno (errno),
586 _("Failed to open file '%s': %s"),
587 filename, g_strerror (errno));
592 return get_contents_stdio (filename, f, contents, length, error);
598 * g_file_get_contents:
599 * @filename: a file to read contents from
600 * @contents: location to store an allocated string
601 * @length: location to store length in bytes of the contents
602 * @error: return location for a #GError
604 * Reads an entire file into allocated memory, with good error
605 * checking. If @error is set, %FALSE is returned, and @contents is set
606 * to %NULL. If %TRUE is returned, @error will not be set, and @contents
607 * will be set to the file contents. The string stored in @contents
608 * will be nul-terminated, so for text files you can pass %NULL for the
609 * @length argument. The error domain is #G_FILE_ERROR. Possible
610 * error codes are those in the #GFileError enumeration.
612 * Return value: %TRUE on success, %FALSE if error is set
615 g_file_get_contents (const gchar *filename,
620 g_return_val_if_fail (filename != NULL, FALSE);
621 g_return_val_if_fail (contents != NULL, FALSE);
628 return get_contents_win32 (filename, contents, length, error);
630 return get_contents_posix (filename, contents, length, error);
635 * mkstemp() implementation is from the GNU C library.
636 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
640 * @tmpl: template filename
642 * Opens a temporary file. See the mkstemp() documentation
643 * on most UNIX-like systems. This is a portability wrapper, which simply calls
644 * mkstemp() on systems that have it, and implements
645 * it in GLib otherwise.
647 * The parameter is a string that should match the rules for
648 * mkstemp(), i.e. end in "XXXXXX". The X string will
649 * be modified to form the name of a file that didn't exist.
651 * Return value: A file handle (as from open()) to the file
652 * opened for reading and writing. The file is opened in binary mode
653 * on platforms where there is a difference. The file handle should be
654 * closed with close(). In case of errors, -1 is returned.
657 g_mkstemp (char *tmpl)
660 return mkstemp (tmpl);
665 static const char letters[] =
666 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
667 static const int NLETTERS = sizeof (letters) - 1;
670 static int counter = 0;
673 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
676 /* This is where the Xs start. */
677 XXXXXX = &tmpl[len - 6];
679 /* Get some more or less random data. */
680 g_get_current_time (&tv);
681 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
683 for (count = 0; count < 100; value += 7777, ++count)
687 /* Fill in the random bits. */
688 XXXXXX[0] = letters[v % NLETTERS];
690 XXXXXX[1] = letters[v % NLETTERS];
692 XXXXXX[2] = letters[v % NLETTERS];
694 XXXXXX[3] = letters[v % NLETTERS];
696 XXXXXX[4] = letters[v % NLETTERS];
698 XXXXXX[5] = letters[v % NLETTERS];
700 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
704 else if (errno != EEXIST)
705 /* Any other error will apply also to other names we might
706 * try, and there are 2^32 or so of them, so give up now.
711 /* We got out of the loop because we ran out of combinations to try. */
718 * @tmpl: Template for file name, as in g_mkstemp(), basename only
719 * @name_used: location to store actual name used
720 * @error: return location for a #GError
722 * Opens a file for writing in the preferred directory for temporary
723 * files (as returned by g_get_tmp_dir()).
725 * @tmpl should be a string ending with six 'X' characters, as the
726 * parameter to g_mkstemp() (or mkstemp()).
727 * However, unlike these functions, the template should only be a
728 * basename, no directory components are allowed. If template is %NULL,
729 * a default template is used.
731 * Note that in contrast to g_mkstemp() (and mkstemp())
732 * @tmpl is not modified, and might thus be a read-only literal string.
734 * The actual name used is returned in @name_used if non-%NULL. This
735 * string should be freed with g_free() when not needed any longer.
737 * Return value: A file handle (as from open()) to
738 * the file opened for reading and writing. The file is opened in binary
739 * mode on platforms where there is a difference. The file handle should be
740 * closed with close(). In case of errors, -1 is returned
741 * and @error will be set.
744 g_file_open_tmp (const char *tmpl,
756 if (strchr (tmpl, G_DIR_SEPARATOR)
758 || strchr (tmpl, '/')
765 _("Template '%s' invalid, should not contain a '%s'"),
766 tmpl, G_DIR_SEPARATOR_S);
771 if (strlen (tmpl) < 6 ||
772 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
777 _("Template '%s' doesn't end with XXXXXX"),
782 tmpdir = g_get_tmp_dir ();
784 if (tmpdir [strlen (tmpdir) - 1] == G_DIR_SEPARATOR)
787 sep = G_DIR_SEPARATOR_S;
789 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
791 retval = g_mkstemp (fulltemplate);
797 g_file_error_from_errno (errno),
798 _("Failed to create file '%s': %s"),
799 fulltemplate, g_strerror (errno));
800 g_free (fulltemplate);
805 *name_used = fulltemplate;
807 g_free (fulltemplate);
813 g_build_pathv (const gchar *separator,
814 const gchar *first_element,
818 gint separator_len = strlen (separator);
819 gboolean is_first = TRUE;
820 gboolean have_leading = FALSE;
821 const gchar *single_element = NULL;
822 const gchar *next_element;
823 const gchar *last_trailing = NULL;
825 result = g_string_new (NULL);
827 next_element = first_element;
831 const gchar *element;
837 element = next_element;
838 next_element = va_arg (args, gchar *);
843 /* Ignore empty elements */
852 strncmp (start, separator, separator_len) == 0)
853 start += separator_len;
856 end = start + strlen (start);
860 while (end >= start + separator_len &&
861 strncmp (end - separator_len, separator, separator_len) == 0)
862 end -= separator_len;
865 while (last_trailing >= element + separator_len &&
866 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
867 last_trailing -= separator_len;
871 /* If the leading and trailing separator strings are in the
872 * same element and overlap, the result is exactly that element
874 if (last_trailing <= start)
875 single_element = element;
877 g_string_append_len (result, element, start - element);
881 single_element = NULL;
888 g_string_append (result, separator);
890 g_string_append_len (result, start, end - start);
896 g_string_free (result, TRUE);
897 return g_strdup (single_element);
902 g_string_append (result, last_trailing);
904 return g_string_free (result, FALSE);
910 * @separator: a string used to separator the elements of the path.
911 * @first_element: the first element in the path
912 * @Varargs: remaining elements in path, terminated by %NULL
914 * Creates a path from a series of elements using @separator as the
915 * separator between elements. At the boundary between two elements,
916 * any trailing occurrences of separator in the first element, or
917 * leading occurrences of separator in the second element are removed
918 * and exactly one copy of the separator is inserted.
920 * Empty elements are ignored.
922 * The number of leading copies of the separator on the result is
923 * the same as the number of leading copies of the separator on
924 * the first non-empty element.
926 * The number of trailing copies of the separator on the result is
927 * the same as the number of trailing copies of the separator on
928 * the last non-empty element. (Determination of the number of
929 * trailing copies is done without stripping leading copies, so
930 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
931 * has 1 trailing copy.)
933 * However, if there is only a single non-empty element, and there
934 * are no characters in that element not part of the leading or
935 * trailing separators, then the result is exactly the original value
938 * Other than for determination of the number of leading and trailing
939 * copies of the separator, elements consisting only of copies
940 * of the separator are ignored.
942 * Return value: a newly-allocated string that must be freed with g_free().
945 g_build_path (const gchar *separator,
946 const gchar *first_element,
952 g_return_val_if_fail (separator != NULL, NULL);
954 va_start (args, first_element);
955 str = g_build_pathv (separator, first_element, args);
963 * @first_element: the first element in the path
964 * @Varargs: remaining elements in path, terminated by %NULL
966 * Creates a filename from a series of elements using the correct
967 * separator for filenames. This function behaves identically
968 * to <literal>g_build_path (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
970 * No attempt is made to force the resulting filename to be an absolute
971 * path. If the first element is a relative path, the result will
972 * be a relative path.
974 * Return value: a newly-allocated string that must be freed with g_free().
977 g_build_filename (const gchar *first_element,
983 va_start (args, first_element);
984 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);