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, (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)
75 * will return TRUE if the file exists; the check whether it's
76 * a directory doesn't matter since the existence test is TRUE.
77 * 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 * Open a temporary file. See "man mkstemp" on most UNIX-like systems.
534 * This is a portability wrapper, which simply calls mkstemp() on systems
535 * that have it, and implements it in GLib otherwise.
537 * The parameter is a string that should match the rules for mktemp, i.e.
538 * end in "XXXXXX". The X string will be modified to form the name
539 * of a file that didn't exist.
541 * Return value: A file handle (as from open()) to the file
542 * opened for reading and writing. The file is opened in binary mode
543 * on platforms where there is a difference. The file handle should be
544 * closed with close(). In case of errors, -1 is returned.
547 g_mkstemp (char *tmpl)
550 return mkstemp (tmpl);
555 static const char letters[] =
556 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
557 static const int NLETTERS = sizeof (letters) - 1;
560 static int counter = 0;
563 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
566 /* This is where the Xs start. */
567 XXXXXX = &tmpl[len - 6];
569 /* Get some more or less random data. */
570 g_get_current_time (&tv);
571 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
573 for (count = 0; count < 100; value += 7777, ++count)
577 /* Fill in the random bits. */
578 XXXXXX[0] = letters[v % NLETTERS];
580 XXXXXX[1] = letters[v % NLETTERS];
582 XXXXXX[2] = letters[v % NLETTERS];
584 XXXXXX[3] = letters[v % NLETTERS];
586 XXXXXX[4] = letters[v % NLETTERS];
588 XXXXXX[5] = letters[v % NLETTERS];
590 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
594 else if (errno != EEXIST)
595 /* Any other error will apply also to other names we might
596 * try, and there are 2^32 or so of them, so give up now.
601 /* We got out of the loop because we ran out of combinations to try. */
608 * @tmpl: Template for file name, as in g_mkstemp, basename only
609 * @name_used: location to store actual name used
610 * @error: return location for a #GError
612 * Opens a file for writing in the preferred directory for temporary
613 * files (as returned by g_get_tmp_dir()).
615 * @tmpl should be a string ending with six 'X' characters, as the
616 * parameter to g_mkstemp() (or mkstemp()). However, unlike these
617 * functions, the template should only be a basename, no directory
618 * components are allowed. If template is NULL, a default template is
621 * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
622 * modified, and might thus be a read-only literal string.
624 * The actual name used is returned in @name_used if non-NULL. This
625 * string should be freed with g_free when not needed any longer.
627 * Return value: A file handle (as from open()) to the file
628 * opened for reading and writing. The file is opened in binary mode
629 * on platforms where there is a difference. The file handle should be
630 * closed with close(). In case of errors, -1 is returned and
631 * @error will be set.
634 g_file_open_tmp (const char *tmpl,
646 if (strchr (tmpl, G_DIR_SEPARATOR)
648 || strchr (tmpl, '/')
655 _("Template '%s' invalid, should not contain a '%s'"),
656 tmpl, G_DIR_SEPARATOR_S);
661 if (strlen (tmpl) < 6 ||
662 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
667 _("Template '%s' doesn't end with XXXXXX"),
672 tmpdir = g_get_tmp_dir ();
674 if (tmpdir [strlen (tmpdir) - 1] == G_DIR_SEPARATOR)
677 sep = G_DIR_SEPARATOR_S;
679 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
681 retval = g_mkstemp (fulltemplate);
687 g_file_error_from_errno (errno),
688 _("Failed to create file '%s': %s"),
689 fulltemplate, strerror (errno));
690 g_free (fulltemplate);
695 *name_used = fulltemplate;
697 g_free (fulltemplate);
703 g_build_pathv (const gchar *separator,
704 const gchar *first_element,
708 gint separator_len = strlen (separator);
709 gboolean is_first = TRUE;
710 const gchar *next_element;
712 result = g_string_new (NULL);
714 next_element = first_element;
718 const gchar *element;
724 element = next_element;
725 next_element = va_arg (args, gchar *);
734 else if (separator_len)
737 strncmp (start, separator, separator_len) == 0)
738 start += separator_len;
741 end = start + strlen (start);
743 if (next_element && separator_len)
745 while (end > start + separator_len &&
746 strncmp (end - separator_len, separator, separator_len) == 0)
747 end -= separator_len;
753 g_string_append (result, separator);
755 g_string_append_len (result, start, end - start);
759 return g_string_free (result, FALSE);
764 * @separator: a string used to separator the elements of the path.
765 * @first_element: the first element in the path
766 * @Varargs: remaining elements in path
768 * Create a path from a series of elements using @separator as the
769 * separator between elements. At the boundary between two elements,
770 * any trailing occurrences of separator in the first element, or
771 * leading occurrences of separator in the second element are removed
772 * and exactly one copy of the separator is inserted.
774 * Return value: a newly allocated string that must be freed with g_free().
777 g_build_path (const gchar *separator,
778 const gchar *first_element,
784 g_return_val_if_fail (separator != NULL, NULL);
786 va_start (args, first_element);
787 str = g_build_pathv (separator, first_element, args);
795 * @first_element: the first element in the path
796 * @Varargs: remaining elements in path
798 * Create a filename from a series of elements using the correct
799 * separator for filenames. This function behaves identically
800 * to g_build_path (G_DIR_SEPARATOR_S, first_element, ....)
802 * No attempt is made to force the resulting filename to be an absolute
803 * path. If the first element is a relative path, the result will
804 * be a relative path.
806 * Return value: a newly allocated string that must be freed with g_free().
809 g_build_filename (const gchar *first_element,
815 va_start (args, first_element);
816 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);