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 * Return value: whether a test was %TRUE
90 g_file_test (const gchar *filename,
93 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
96 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
99 if (test & G_FILE_TEST_IS_SYMLINK)
102 /* no sym links on win32, no lstat in msvcrt */
106 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
111 if (test & (G_FILE_TEST_IS_REGULAR | G_FILE_TEST_IS_DIR))
115 if (stat (filename, &s) == 0)
117 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
120 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
129 g_file_error_quark (void)
133 q = g_quark_from_static_string ("g-file-error-quark");
139 * g_file_error_from_errno:
140 * @err_no: an "errno" value
142 * Gets a #GFileError constant based on the passed-in @errno.
143 * For example, if you pass in %EEXIST this function returns
144 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
145 * assume that all #GFileError values will exist.
147 * Normally a #GFileError value goes into a #GError returned
148 * from a function that manipulates files. So you would use
149 * g_file_error_from_errno() when constructing a #GError.
151 * Return value: #GFileError corresponding to the given @errno
154 g_file_error_from_errno (gint err_no)
160 return G_FILE_ERROR_EXIST;
166 return G_FILE_ERROR_ISDIR;
172 return G_FILE_ERROR_ACCES;
178 return G_FILE_ERROR_NAMETOOLONG;
184 return G_FILE_ERROR_NOENT;
190 return G_FILE_ERROR_NOTDIR;
196 return G_FILE_ERROR_NXIO;
202 return G_FILE_ERROR_NODEV;
208 return G_FILE_ERROR_ROFS;
214 return G_FILE_ERROR_TXTBSY;
220 return G_FILE_ERROR_FAULT;
226 return G_FILE_ERROR_LOOP;
232 return G_FILE_ERROR_NOSPC;
238 return G_FILE_ERROR_NOMEM;
244 return G_FILE_ERROR_MFILE;
250 return G_FILE_ERROR_NFILE;
256 return G_FILE_ERROR_BADF;
262 return G_FILE_ERROR_INVAL;
268 return G_FILE_ERROR_PIPE;
274 return G_FILE_ERROR_AGAIN;
280 return G_FILE_ERROR_INTR;
286 return G_FILE_ERROR_IO;
292 return G_FILE_ERROR_PERM;
297 return G_FILE_ERROR_FAILED;
303 get_contents_stdio (const gchar *filename,
313 size_t total_allocated;
315 g_assert (f != NULL);
317 #define STARTING_ALLOC 64
320 total_allocated = STARTING_ALLOC;
321 str = g_malloc (STARTING_ALLOC);
325 bytes = fread (buf, 1, 2048, f);
327 while ((total_bytes + bytes + 1) > total_allocated)
329 total_allocated *= 2;
330 str = g_try_realloc (str, total_allocated);
337 _("Could not allocate %lu bytes to read file \"%s\""),
338 (gulong) total_allocated, filename);
347 g_file_error_from_errno (errno),
348 _("Error reading file '%s': %s"),
349 filename, g_strerror (errno));
354 memcpy (str + total_bytes, buf, bytes);
355 total_bytes += bytes;
360 str[total_bytes] = '\0';
363 *length = total_bytes;
380 get_contents_regfile (const gchar *filename,
381 struct stat *stat_buf,
392 size = stat_buf->st_size;
394 alloc_size = size + 1;
395 buf = g_try_malloc (alloc_size);
402 _("Could not allocate %lu bytes to read file \"%s\""),
403 (gulong) alloc_size, filename);
409 while (bytes_read < size)
413 rc = read (fd, buf + bytes_read, size - bytes_read);
425 g_file_error_from_errno (errno),
426 _("Failed to read from file '%s': %s"),
427 filename, g_strerror (errno));
438 buf[bytes_read] = '\0';
441 *length = bytes_read;
457 get_contents_posix (const gchar *filename,
462 struct stat stat_buf;
465 /* O_BINARY useful on Cygwin */
466 fd = open (filename, O_RDONLY|O_BINARY);
472 g_file_error_from_errno (errno),
473 _("Failed to open file '%s': %s"),
474 filename, g_strerror (errno));
479 /* I don't think this will ever fail, aside from ENOMEM, but. */
480 if (fstat (fd, &stat_buf) < 0)
486 g_file_error_from_errno (errno),
487 _("Failed to get attributes of file '%s': fstat() failed: %s"),
488 filename, g_strerror (errno));
493 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
495 return get_contents_regfile (filename,
506 f = fdopen (fd, "r");
512 g_file_error_from_errno (errno),
513 _("Failed to open file '%s': fdopen() failed: %s"),
514 filename, g_strerror (errno));
519 return get_contents_stdio (filename, f, contents, length, error);
523 #else /* G_OS_WIN32 */
526 get_contents_win32 (const gchar *filename,
533 /* I guess you want binary mode; maybe you want text sometimes? */
534 f = fopen (filename, "rb");
540 g_file_error_from_errno (errno),
541 _("Failed to open file '%s': %s"),
542 filename, g_strerror (errno));
547 return get_contents_stdio (filename, f, contents, length, error);
553 * g_file_get_contents:
554 * @filename: a file to read contents from
555 * @contents: location to store an allocated string
556 * @length: location to store length in bytes of the contents
557 * @error: return location for a #GError
559 * Reads an entire file into allocated memory, with good error
560 * checking. If @error is set, %FALSE is returned, and @contents is set
561 * to %NULL. If %TRUE is returned, @error will not be set, and @contents
562 * will be set to the file contents. The string stored in @contents
563 * will be nul-terminated, so for text files you can pass %NULL for the
564 * @length argument. The error domain is #G_FILE_ERROR. Possible
565 * error codes are those in the #GFileError enumeration.
567 * Return value: %TRUE on success, %FALSE if error is set
570 g_file_get_contents (const gchar *filename,
575 g_return_val_if_fail (filename != NULL, FALSE);
576 g_return_val_if_fail (contents != NULL, FALSE);
583 return get_contents_win32 (filename, contents, length, error);
585 return get_contents_posix (filename, contents, length, error);
590 * mkstemp() implementation is from the GNU C library.
591 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
595 * @tmpl: template filename
597 * Opens a temporary file. See the <function>mkstemp()</function> documentation
598 * on most UNIX-like systems. This is a portability wrapper, which simply calls
599 * <function>mkstemp()</function> on systems that have it, and implements
600 * it in GLib otherwise.
602 * The parameter is a string that should match the rules for
603 * <function>mkstemp()</function>, i.e. end in "XXXXXX". The X string will
604 * be modified to form the name of a file that didn't exist.
606 * Return value: A file handle (as from <function>open()</function>) to the file
607 * opened for reading and writing. The file is opened in binary mode
608 * on platforms where there is a difference. The file handle should be
609 * closed with <function>close()</function>. In case of errors, -1 is returned.
612 g_mkstemp (char *tmpl)
615 return mkstemp (tmpl);
620 static const char letters[] =
621 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
622 static const int NLETTERS = sizeof (letters) - 1;
625 static int counter = 0;
628 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
631 /* This is where the Xs start. */
632 XXXXXX = &tmpl[len - 6];
634 /* Get some more or less random data. */
635 g_get_current_time (&tv);
636 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
638 for (count = 0; count < 100; value += 7777, ++count)
642 /* Fill in the random bits. */
643 XXXXXX[0] = letters[v % NLETTERS];
645 XXXXXX[1] = letters[v % NLETTERS];
647 XXXXXX[2] = letters[v % NLETTERS];
649 XXXXXX[3] = letters[v % NLETTERS];
651 XXXXXX[4] = letters[v % NLETTERS];
653 XXXXXX[5] = letters[v % NLETTERS];
655 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
659 else if (errno != EEXIST)
660 /* Any other error will apply also to other names we might
661 * try, and there are 2^32 or so of them, so give up now.
666 /* We got out of the loop because we ran out of combinations to try. */
673 * @tmpl: Template for file name, as in g_mkstemp(), basename only
674 * @name_used: location to store actual name used
675 * @error: return location for a #GError
677 * Opens a file for writing in the preferred directory for temporary
678 * files (as returned by g_get_tmp_dir()).
680 * @tmpl should be a string ending with six 'X' characters, as the
681 * parameter to g_mkstemp() (or <function>mkstemp()</function>).
682 * However, unlike these functions, the template should only be a
683 * basename, no directory components are allowed. If template is %NULL,
684 * a default template is used.
686 * Note that in contrast to g_mkstemp() (and <function>mkstemp()</function>)
687 * @tmpl is not modified, and might thus be a read-only literal string.
689 * The actual name used is returned in @name_used if non-%NULL. This
690 * string should be freed with g_free() when not needed any longer.
692 * Return value: A file handle (as from <function>open()</function>) to
693 * the file opened for reading and writing. The file is opened in binary
694 * mode on platforms where there is a difference. The file handle should be
695 * closed with <function>close()</function>. In case of errors, -1 is returned
696 * and @error will be set.
699 g_file_open_tmp (const char *tmpl,
711 if (strchr (tmpl, G_DIR_SEPARATOR)
713 || strchr (tmpl, '/')
720 _("Template '%s' invalid, should not contain a '%s'"),
721 tmpl, G_DIR_SEPARATOR_S);
726 if (strlen (tmpl) < 6 ||
727 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
732 _("Template '%s' doesn't end with XXXXXX"),
737 tmpdir = g_get_tmp_dir ();
739 if (tmpdir [strlen (tmpdir) - 1] == G_DIR_SEPARATOR)
742 sep = G_DIR_SEPARATOR_S;
744 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
746 retval = g_mkstemp (fulltemplate);
752 g_file_error_from_errno (errno),
753 _("Failed to create file '%s': %s"),
754 fulltemplate, g_strerror (errno));
755 g_free (fulltemplate);
760 *name_used = fulltemplate;
762 g_free (fulltemplate);
768 g_build_pathv (const gchar *separator,
769 const gchar *first_element,
773 gint separator_len = strlen (separator);
774 gboolean is_first = TRUE;
775 const gchar *next_element;
777 result = g_string_new (NULL);
779 next_element = first_element;
783 const gchar *element;
789 element = next_element;
790 next_element = va_arg (args, gchar *);
799 else if (separator_len)
802 strncmp (start, separator, separator_len) == 0)
803 start += separator_len;
806 end = start + strlen (start);
808 if (next_element && separator_len)
810 while (end > start + separator_len &&
811 strncmp (end - separator_len, separator, separator_len) == 0)
812 end -= separator_len;
818 g_string_append (result, separator);
820 g_string_append_len (result, start, end - start);
824 return g_string_free (result, FALSE);
829 * @separator: a string used to separator the elements of the path.
830 * @first_element: the first element in the path
831 * @Varargs: remaining elements in path
833 * Creates a path from a series of elements using @separator as the
834 * separator between elements. At the boundary between two elements,
835 * any trailing occurrences of separator in the first element, or
836 * leading occurrences of separator in the second element are removed
837 * and exactly one copy of the separator is inserted.
839 * Return value: a newly-allocated string that must be freed with g_free().
842 g_build_path (const gchar *separator,
843 const gchar *first_element,
849 g_return_val_if_fail (separator != NULL, NULL);
851 va_start (args, first_element);
852 str = g_build_pathv (separator, first_element, args);
860 * @first_element: the first element in the path
861 * @Varargs: remaining elements in path
863 * Creates a filename from a series of elements using the correct
864 * separator for filenames. This function behaves identically
865 * to <literal>g_build_path (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
867 * No attempt is made to force the resulting filename to be an absolute
868 * path. If the first element is a relative path, the result will
869 * be a relative path.
871 * Return value: a newly-allocated string that must be freed with g_free().
874 g_build_filename (const gchar *first_element,
880 va_start (args, first_element);
881 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);