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 size_t total_allocated;
298 g_assert (f != NULL);
300 #define STARTING_ALLOC 64
303 total_allocated = STARTING_ALLOC;
304 str = g_malloc (STARTING_ALLOC);
308 bytes = fread (buf, 1, 2048, f);
310 while ((total_bytes + bytes + 1) > total_allocated)
312 total_allocated *= 2;
313 str = g_try_realloc (str, total_allocated);
320 _("Could not allocate %lu bytes to read file \"%s\""),
321 (gulong) total_allocated, filename);
330 g_file_error_from_errno (errno),
331 _("Error reading file '%s': %s"),
332 filename, strerror (errno));
337 memcpy (str + total_bytes, buf, bytes);
338 total_bytes += bytes;
343 str[total_bytes] = '\0';
346 *length = total_bytes;
363 get_contents_regfile (const gchar *filename,
364 struct stat *stat_buf,
375 size = stat_buf->st_size;
377 alloc_size = size + 1;
378 buf = g_try_malloc (alloc_size);
385 _("Could not allocate %lu bytes to read file \"%s\""),
386 (gulong) alloc_size, filename);
392 while (bytes_read < size)
396 rc = read (fd, buf + bytes_read, size - bytes_read);
408 g_file_error_from_errno (errno),
409 _("Failed to read from file '%s': %s"),
410 filename, strerror (errno));
421 buf[bytes_read] = '\0';
424 *length = bytes_read;
432 get_contents_posix (const gchar *filename,
437 struct stat stat_buf;
440 /* O_BINARY useful on Cygwin */
441 fd = open (filename, O_RDONLY|O_BINARY);
447 g_file_error_from_errno (errno),
448 _("Failed to open file '%s': %s"),
449 filename, strerror (errno));
454 /* I don't think this will ever fail, aside from ENOMEM, but. */
455 if (fstat (fd, &stat_buf) < 0)
461 g_file_error_from_errno (errno),
462 _("Failed to get attributes of file '%s': fstat() failed: %s"),
463 filename, strerror (errno));
468 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
470 return get_contents_regfile (filename,
481 f = fdopen (fd, "r");
487 g_file_error_from_errno (errno),
488 _("Failed to open file '%s': fdopen() failed: %s"),
489 filename, strerror (errno));
494 return get_contents_stdio (filename, f, contents, length, error);
498 #else /* G_OS_WIN32 */
501 get_contents_win32 (const gchar *filename,
508 /* I guess you want binary mode; maybe you want text sometimes? */
509 f = fopen (filename, "rb");
515 g_file_error_from_errno (errno),
516 _("Failed to open file '%s': %s"),
517 filename, strerror (errno));
522 return get_contents_stdio (filename, f, contents, length, error);
528 * g_file_get_contents:
529 * @filename: a file to read contents from
530 * @contents: location to store an allocated string
531 * @length: location to store length in bytes of the contents
532 * @error: return location for a #GError
534 * Reads an entire file into allocated memory, with good error
535 * checking. If @error is set, %FALSE is returned, and @contents is set
536 * to %NULL. If %TRUE is returned, @error will not be set, and @contents
537 * will be set to the file contents. The string stored in @contents
538 * will be nul-terminated, so for text files you can pass %NULL for the
539 * @length argument. The error domain is #G_FILE_ERROR. Possible
540 * error codes are those in the #GFileError enumeration.
542 * FIXME currently crashes if the file is too big to fit in memory;
543 * should probably use g_try_malloc() when we have that function.
545 * Return value: %TRUE on success, %FALSE if error is set
548 g_file_get_contents (const gchar *filename,
553 g_return_val_if_fail (filename != NULL, FALSE);
554 g_return_val_if_fail (contents != NULL, FALSE);
561 return get_contents_win32 (filename, contents, length, error);
563 return get_contents_posix (filename, contents, length, error);
568 * mkstemp() implementation is from the GNU C library.
569 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
573 * @tmpl: template filename
575 * Opens a temporary file. See the <function>mkstemp()</function> documentation
576 * on most UNIX-like systems. This is a portability wrapper, which simply calls
577 * <function>mkstemp()</function> on systems that have it, and implements
578 * it in GLib otherwise.
580 * The parameter is a string that should match the rules for
581 * <function>mkstemp()</function>, i.e. end in "XXXXXX". The X string will
582 * be modified to form the name of a file that didn't exist.
584 * Return value: A file handle (as from <function>open()</function>) to the file
585 * opened for reading and writing. The file is opened in binary mode
586 * on platforms where there is a difference. The file handle should be
587 * closed with <function>close()</function>. In case of errors, -1 is returned.
590 g_mkstemp (char *tmpl)
593 return mkstemp (tmpl);
598 static const char letters[] =
599 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
600 static const int NLETTERS = sizeof (letters) - 1;
603 static int counter = 0;
606 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
609 /* This is where the Xs start. */
610 XXXXXX = &tmpl[len - 6];
612 /* Get some more or less random data. */
613 g_get_current_time (&tv);
614 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
616 for (count = 0; count < 100; value += 7777, ++count)
620 /* Fill in the random bits. */
621 XXXXXX[0] = letters[v % NLETTERS];
623 XXXXXX[1] = letters[v % NLETTERS];
625 XXXXXX[2] = letters[v % NLETTERS];
627 XXXXXX[3] = letters[v % NLETTERS];
629 XXXXXX[4] = letters[v % NLETTERS];
631 XXXXXX[5] = letters[v % NLETTERS];
633 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
637 else if (errno != EEXIST)
638 /* Any other error will apply also to other names we might
639 * try, and there are 2^32 or so of them, so give up now.
644 /* We got out of the loop because we ran out of combinations to try. */
651 * @tmpl: Template for file name, as in g_mkstemp(), basename only
652 * @name_used: location to store actual name used
653 * @error: return location for a #GError
655 * Opens a file for writing in the preferred directory for temporary
656 * files (as returned by g_get_tmp_dir()).
658 * @tmpl should be a string ending with six 'X' characters, as the
659 * parameter to g_mkstemp() (or <function>mkstemp()</function>).
660 * However, unlike these functions, the template should only be a
661 * basename, no directory components are allowed. If template is %NULL,
662 * a default template is used.
664 * Note that in contrast to g_mkstemp() (and <function>mkstemp()</function>)
665 * @tmpl is not modified, and might thus be a read-only literal string.
667 * The actual name used is returned in @name_used if non-%NULL. This
668 * string should be freed with g_free() when not needed any longer.
670 * Return value: A file handle (as from <function>open()</function>) to
671 * the file opened for reading and writing. The file is opened in binary
672 * mode on platforms where there is a difference. The file handle should be
673 * closed with <function>close()</function>. In case of errors, -1 is returned
674 * and @error will be set.
677 g_file_open_tmp (const char *tmpl,
689 if (strchr (tmpl, G_DIR_SEPARATOR)
691 || strchr (tmpl, '/')
698 _("Template '%s' invalid, should not contain a '%s'"),
699 tmpl, G_DIR_SEPARATOR_S);
704 if (strlen (tmpl) < 6 ||
705 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
710 _("Template '%s' doesn't end with XXXXXX"),
715 tmpdir = g_get_tmp_dir ();
717 if (tmpdir [strlen (tmpdir) - 1] == G_DIR_SEPARATOR)
720 sep = G_DIR_SEPARATOR_S;
722 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
724 retval = g_mkstemp (fulltemplate);
730 g_file_error_from_errno (errno),
731 _("Failed to create file '%s': %s"),
732 fulltemplate, strerror (errno));
733 g_free (fulltemplate);
738 *name_used = fulltemplate;
740 g_free (fulltemplate);
746 g_build_pathv (const gchar *separator,
747 const gchar *first_element,
751 gint separator_len = strlen (separator);
752 gboolean is_first = TRUE;
753 const gchar *next_element;
755 result = g_string_new (NULL);
757 next_element = first_element;
761 const gchar *element;
767 element = next_element;
768 next_element = va_arg (args, gchar *);
777 else if (separator_len)
780 strncmp (start, separator, separator_len) == 0)
781 start += separator_len;
784 end = start + strlen (start);
786 if (next_element && separator_len)
788 while (end > start + separator_len &&
789 strncmp (end - separator_len, separator, separator_len) == 0)
790 end -= separator_len;
796 g_string_append (result, separator);
798 g_string_append_len (result, start, end - start);
802 return g_string_free (result, FALSE);
807 * @separator: a string used to separator the elements of the path.
808 * @first_element: the first element in the path
809 * @Varargs: remaining elements in path
811 * Creates a path from a series of elements using @separator as the
812 * separator between elements. At the boundary between two elements,
813 * any trailing occurrences of separator in the first element, or
814 * leading occurrences of separator in the second element are removed
815 * and exactly one copy of the separator is inserted.
817 * Return value: a newly-allocated string that must be freed with g_free().
820 g_build_path (const gchar *separator,
821 const gchar *first_element,
827 g_return_val_if_fail (separator != NULL, NULL);
829 va_start (args, first_element);
830 str = g_build_pathv (separator, first_element, args);
838 * @first_element: the first element in the path
839 * @Varargs: remaining elements in path
841 * Creates a filename from a series of elements using the correct
842 * separator for filenames. This function behaves identically
843 * to <literal>g_build_path (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
845 * No attempt is made to force the resulting filename to be an absolute
846 * path. If the first element is a relative path, the result will
847 * be a relative path.
849 * Return value: a newly-allocated string that must be freed with g_free().
852 g_build_filename (const gchar *first_element,
858 va_start (args, first_element);
859 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);