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 * Return value: whether a test was %TRUE
83 g_file_test (const gchar *filename,
86 if (test & G_FILE_TEST_EXISTS)
87 return (access (filename, F_OK) == 0);
88 else if (test & G_FILE_TEST_IS_EXECUTABLE)
89 return (access (filename, X_OK) == 0);
94 if (stat (filename, &s) < 0)
97 if ((test & G_FILE_TEST_IS_REGULAR) &&
100 else if ((test & G_FILE_TEST_IS_DIR) &&
103 else if ((test & G_FILE_TEST_IS_SYMLINK) &&
112 g_file_error_quark (void)
116 q = g_quark_from_static_string ("g-file-error-quark");
122 * g_file_error_from_errno:
123 * @err_no: an "errno" value
125 * Gets a #GFileError constant based on the passed-in @errno.
126 * For example, if you pass in %EEXIST this function returns
127 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
128 * assume that all #GFileError values will exist.
130 * Normally a #GFileError value goes into a #GError returned
131 * from a function that manipulates files. So you would use
132 * g_file_error_from_errno() when constructing a #GError.
134 * Return value: #GFileError corresponding to the given @errno
137 g_file_error_from_errno (gint err_no)
143 return G_FILE_ERROR_EXIST;
149 return G_FILE_ERROR_ISDIR;
155 return G_FILE_ERROR_ACCES;
161 return G_FILE_ERROR_NAMETOOLONG;
167 return G_FILE_ERROR_NOENT;
173 return G_FILE_ERROR_NOTDIR;
179 return G_FILE_ERROR_NXIO;
185 return G_FILE_ERROR_NODEV;
191 return G_FILE_ERROR_ROFS;
197 return G_FILE_ERROR_TXTBSY;
203 return G_FILE_ERROR_FAULT;
209 return G_FILE_ERROR_LOOP;
215 return G_FILE_ERROR_NOSPC;
221 return G_FILE_ERROR_NOMEM;
227 return G_FILE_ERROR_MFILE;
233 return G_FILE_ERROR_NFILE;
239 return G_FILE_ERROR_BADF;
245 return G_FILE_ERROR_INVAL;
251 return G_FILE_ERROR_PIPE;
257 return G_FILE_ERROR_AGAIN;
263 return G_FILE_ERROR_INTR;
269 return G_FILE_ERROR_IO;
275 return G_FILE_ERROR_PERM;
280 return G_FILE_ERROR_FAILED;
286 get_contents_stdio (const gchar *filename,
296 g_assert (f != NULL);
298 str = g_string_new ("");
302 bytes = fread (buf, 1, 2048, f);
308 g_file_error_from_errno (errno),
309 _("Error reading file '%s': %s"),
310 filename, strerror (errno));
312 g_string_free (str, TRUE);
318 g_string_append_len (str, buf, bytes);
326 *contents = g_string_free (str, FALSE);
334 get_contents_regfile (const gchar *filename,
335 struct stat *stat_buf,
345 size = stat_buf->st_size;
347 buf = g_new (gchar, size + 1);
350 while (bytes_read < size)
354 rc = read (fd, buf + bytes_read, size - bytes_read);
366 g_file_error_from_errno (errno),
367 _("Failed to read from file '%s': %s"),
368 filename, strerror (errno));
379 buf[bytes_read] = '\0';
382 *length = bytes_read;
390 get_contents_posix (const gchar *filename,
395 struct stat stat_buf;
398 /* O_BINARY useful on Cygwin */
399 fd = open (filename, O_RDONLY|O_BINARY);
405 g_file_error_from_errno (errno),
406 _("Failed to open file '%s': %s"),
407 filename, strerror (errno));
412 /* I don't think this will ever fail, aside from ENOMEM, but. */
413 if (fstat (fd, &stat_buf) < 0)
419 g_file_error_from_errno (errno),
420 _("Failed to get attributes of file '%s': fstat() failed: %s"),
421 filename, strerror (errno));
426 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
428 return get_contents_regfile (filename,
439 f = fdopen (fd, "r");
445 g_file_error_from_errno (errno),
446 _("Failed to open file '%s': fdopen() failed: %s"),
447 filename, strerror (errno));
452 return get_contents_stdio (filename, f, contents, length, error);
456 #else /* G_OS_WIN32 */
459 get_contents_win32 (const gchar *filename,
466 /* I guess you want binary mode; maybe you want text sometimes? */
467 f = fopen (filename, "rb");
473 g_file_error_from_errno (errno),
474 _("Failed to open file '%s': %s"),
475 filename, strerror (errno));
480 return get_contents_stdio (filename, f, contents, length, error);
486 * g_file_get_contents:
487 * @filename: a file to read contents from
488 * @contents: location to store an allocated string
489 * @length: location to store length in bytes of the contents
490 * @error: return location for a #GError
492 * Reads an entire file into allocated memory, with good error
493 * checking. If @error is set, %FALSE is returned, and @contents is set
494 * to %NULL. If %TRUE is returned, @error will not be set, and @contents
495 * will be set to the file contents. The string stored in @contents
496 * will be nul-terminated, so for text files you can pass %NULL for the
497 * @length argument. The error domain is #G_FILE_ERROR. Possible
498 * error codes are those in the #GFileError enumeration.
500 * FIXME currently crashes if the file is too big to fit in memory;
501 * should probably use g_try_malloc() when we have that function.
503 * Return value: %TRUE on success, %FALSE if error is set
506 g_file_get_contents (const gchar *filename,
511 g_return_val_if_fail (filename != NULL, FALSE);
512 g_return_val_if_fail (contents != NULL, FALSE);
519 return get_contents_win32 (filename, contents, length, error);
521 return get_contents_posix (filename, contents, length, error);
526 * mkstemp() implementation is from the GNU C library.
527 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
531 * @tmpl: template filename
533 * Opens a temporary file. See the <function>mkstemp()</function> documentation
534 * on most UNIX-like systems. This is a portability wrapper, which simply calls
535 * <function>mkstemp()</function> on systems that have it, and implements
536 * it in GLib otherwise.
538 * The parameter is a string that should match the rules for
539 * <function>mkstemp()</function>, i.e. end in "XXXXXX". The X string will
540 * be modified to form the name of a file that didn't exist.
542 * Return value: A file handle (as from <function>open()</function>) to the file
543 * opened for reading and writing. The file is opened in binary mode
544 * on platforms where there is a difference. The file handle should be
545 * closed with <function>close()</function>. In case of errors, -1 is returned.
548 g_mkstemp (char *tmpl)
551 return mkstemp (tmpl);
556 static const char letters[] =
557 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
558 static const int NLETTERS = sizeof (letters) - 1;
561 static int counter = 0;
564 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
567 /* This is where the Xs start. */
568 XXXXXX = &tmpl[len - 6];
570 /* Get some more or less random data. */
571 g_get_current_time (&tv);
572 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
574 for (count = 0; count < 100; value += 7777, ++count)
578 /* Fill in the random bits. */
579 XXXXXX[0] = letters[v % NLETTERS];
581 XXXXXX[1] = letters[v % NLETTERS];
583 XXXXXX[2] = letters[v % NLETTERS];
585 XXXXXX[3] = letters[v % NLETTERS];
587 XXXXXX[4] = letters[v % NLETTERS];
589 XXXXXX[5] = letters[v % NLETTERS];
591 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
595 else if (errno != EEXIST)
596 /* Any other error will apply also to other names we might
597 * try, and there are 2^32 or so of them, so give up now.
602 /* We got out of the loop because we ran out of combinations to try. */
609 * @tmpl: Template for file name, as in g_mkstemp(), basename only
610 * @name_used: location to store actual name used
611 * @error: return location for a #GError
613 * Opens a file for writing in the preferred directory for temporary
614 * files (as returned by g_get_tmp_dir()).
616 * @tmpl should be a string ending with six 'X' characters, as the
617 * parameter to g_mkstemp() (or <function>mkstemp()</function>).
618 * However, unlike these functions, the template should only be a
619 * basename, no directory components are allowed. If template is %NULL,
620 * a default template is used.
622 * Note that in contrast to g_mkstemp() (and <function>mkstemp()</function>)
623 * @tmpl is not modified, and might thus be a read-only literal string.
625 * The actual name used is returned in @name_used if non-%NULL. This
626 * string should be freed with g_free() when not needed any longer.
628 * Return value: A file handle (as from <function>open()</function>) to
629 * the file opened for reading and writing. The file is opened in binary
630 * mode on platforms where there is a difference. The file handle should be
631 * closed with <function>close()</function>. In case of errors, -1 is returned
632 * and @error will be set.
635 g_file_open_tmp (const char *tmpl,
647 if (strchr (tmpl, G_DIR_SEPARATOR)
649 || strchr (tmpl, '/')
656 _("Template '%s' invalid, should not contain a '%s'"),
657 tmpl, G_DIR_SEPARATOR_S);
662 if (strlen (tmpl) < 6 ||
663 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
668 _("Template '%s' doesn't end with XXXXXX"),
673 tmpdir = g_get_tmp_dir ();
675 if (tmpdir [strlen (tmpdir) - 1] == G_DIR_SEPARATOR)
678 sep = G_DIR_SEPARATOR_S;
680 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
682 retval = g_mkstemp (fulltemplate);
688 g_file_error_from_errno (errno),
689 _("Failed to create file '%s': %s"),
690 fulltemplate, strerror (errno));
691 g_free (fulltemplate);
696 *name_used = fulltemplate;
698 g_free (fulltemplate);
704 g_build_pathv (const gchar *separator,
705 const gchar *first_element,
709 gint separator_len = strlen (separator);
710 gboolean is_first = TRUE;
711 const gchar *next_element;
713 result = g_string_new (NULL);
715 next_element = first_element;
719 const gchar *element;
725 element = next_element;
726 next_element = va_arg (args, gchar *);
735 else if (separator_len)
738 strncmp (start, separator, separator_len) == 0)
739 start += separator_len;
742 end = start + strlen (start);
744 if (next_element && separator_len)
746 while (end > start + separator_len &&
747 strncmp (end - separator_len, separator, separator_len) == 0)
748 end -= separator_len;
754 g_string_append (result, separator);
756 g_string_append_len (result, start, end - start);
760 return g_string_free (result, FALSE);
765 * @separator: a string used to separator the elements of the path.
766 * @first_element: the first element in the path
767 * @Varargs: remaining elements in path
769 * Creates a path from a series of elements using @separator as the
770 * separator between elements. At the boundary between two elements,
771 * any trailing occurrences of separator in the first element, or
772 * leading occurrences of separator in the second element are removed
773 * and exactly one copy of the separator is inserted.
775 * Return value: a newly-allocated string that must be freed with g_free().
778 g_build_path (const gchar *separator,
779 const gchar *first_element,
785 g_return_val_if_fail (separator != NULL, NULL);
787 va_start (args, first_element);
788 str = g_build_pathv (separator, first_element, args);
796 * @first_element: the first element in the path
797 * @Varargs: remaining elements in path
799 * Creates a filename from a series of elements using the correct
800 * separator for filenames. This function behaves identically
801 * to <literal>g_build_path (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
803 * No attempt is made to force the resulting filename to be an absolute
804 * path. If the first element is a relative path, the result will
805 * be a relative path.
807 * Return value: a newly-allocated string that must be freed with g_free().
810 g_build_filename (const gchar *first_element,
816 va_start (args, first_element);
817 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);