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)
103 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
107 if (test & (G_FILE_TEST_IS_REGULAR | G_FILE_TEST_IS_DIR))
111 if (stat (filename, &s) == 0)
113 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
116 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
125 g_file_error_quark (void)
129 q = g_quark_from_static_string ("g-file-error-quark");
135 * g_file_error_from_errno:
136 * @err_no: an "errno" value
138 * Gets a #GFileError constant based on the passed-in @errno.
139 * For example, if you pass in %EEXIST this function returns
140 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
141 * assume that all #GFileError values will exist.
143 * Normally a #GFileError value goes into a #GError returned
144 * from a function that manipulates files. So you would use
145 * g_file_error_from_errno() when constructing a #GError.
147 * Return value: #GFileError corresponding to the given @errno
150 g_file_error_from_errno (gint err_no)
156 return G_FILE_ERROR_EXIST;
162 return G_FILE_ERROR_ISDIR;
168 return G_FILE_ERROR_ACCES;
174 return G_FILE_ERROR_NAMETOOLONG;
180 return G_FILE_ERROR_NOENT;
186 return G_FILE_ERROR_NOTDIR;
192 return G_FILE_ERROR_NXIO;
198 return G_FILE_ERROR_NODEV;
204 return G_FILE_ERROR_ROFS;
210 return G_FILE_ERROR_TXTBSY;
216 return G_FILE_ERROR_FAULT;
222 return G_FILE_ERROR_LOOP;
228 return G_FILE_ERROR_NOSPC;
234 return G_FILE_ERROR_NOMEM;
240 return G_FILE_ERROR_MFILE;
246 return G_FILE_ERROR_NFILE;
252 return G_FILE_ERROR_BADF;
258 return G_FILE_ERROR_INVAL;
264 return G_FILE_ERROR_PIPE;
270 return G_FILE_ERROR_AGAIN;
276 return G_FILE_ERROR_INTR;
282 return G_FILE_ERROR_IO;
288 return G_FILE_ERROR_PERM;
293 return G_FILE_ERROR_FAILED;
299 get_contents_stdio (const gchar *filename,
309 size_t total_allocated;
311 g_assert (f != NULL);
313 #define STARTING_ALLOC 64
316 total_allocated = STARTING_ALLOC;
317 str = g_malloc (STARTING_ALLOC);
321 bytes = fread (buf, 1, 2048, f);
323 while ((total_bytes + bytes + 1) > total_allocated)
325 total_allocated *= 2;
326 str = g_try_realloc (str, total_allocated);
333 _("Could not allocate %lu bytes to read file \"%s\""),
334 (gulong) total_allocated, filename);
343 g_file_error_from_errno (errno),
344 _("Error reading file '%s': %s"),
345 filename, strerror (errno));
350 memcpy (str + total_bytes, buf, bytes);
351 total_bytes += bytes;
356 str[total_bytes] = '\0';
359 *length = total_bytes;
376 get_contents_regfile (const gchar *filename,
377 struct stat *stat_buf,
388 size = stat_buf->st_size;
390 alloc_size = size + 1;
391 buf = g_try_malloc (alloc_size);
398 _("Could not allocate %lu bytes to read file \"%s\""),
399 (gulong) alloc_size, filename);
405 while (bytes_read < size)
409 rc = read (fd, buf + bytes_read, size - bytes_read);
421 g_file_error_from_errno (errno),
422 _("Failed to read from file '%s': %s"),
423 filename, strerror (errno));
434 buf[bytes_read] = '\0';
437 *length = bytes_read;
445 get_contents_posix (const gchar *filename,
450 struct stat stat_buf;
453 /* O_BINARY useful on Cygwin */
454 fd = open (filename, O_RDONLY|O_BINARY);
460 g_file_error_from_errno (errno),
461 _("Failed to open file '%s': %s"),
462 filename, strerror (errno));
467 /* I don't think this will ever fail, aside from ENOMEM, but. */
468 if (fstat (fd, &stat_buf) < 0)
474 g_file_error_from_errno (errno),
475 _("Failed to get attributes of file '%s': fstat() failed: %s"),
476 filename, strerror (errno));
481 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
483 return get_contents_regfile (filename,
494 f = fdopen (fd, "r");
500 g_file_error_from_errno (errno),
501 _("Failed to open file '%s': fdopen() failed: %s"),
502 filename, strerror (errno));
507 return get_contents_stdio (filename, f, contents, length, error);
511 #else /* G_OS_WIN32 */
514 get_contents_win32 (const gchar *filename,
521 /* I guess you want binary mode; maybe you want text sometimes? */
522 f = fopen (filename, "rb");
528 g_file_error_from_errno (errno),
529 _("Failed to open file '%s': %s"),
530 filename, strerror (errno));
535 return get_contents_stdio (filename, f, contents, length, error);
541 * g_file_get_contents:
542 * @filename: a file to read contents from
543 * @contents: location to store an allocated string
544 * @length: location to store length in bytes of the contents
545 * @error: return location for a #GError
547 * Reads an entire file into allocated memory, with good error
548 * checking. If @error is set, %FALSE is returned, and @contents is set
549 * to %NULL. If %TRUE is returned, @error will not be set, and @contents
550 * will be set to the file contents. The string stored in @contents
551 * will be nul-terminated, so for text files you can pass %NULL for the
552 * @length argument. The error domain is #G_FILE_ERROR. Possible
553 * error codes are those in the #GFileError enumeration.
555 * Return value: %TRUE on success, %FALSE if error is set
558 g_file_get_contents (const gchar *filename,
563 g_return_val_if_fail (filename != NULL, FALSE);
564 g_return_val_if_fail (contents != NULL, FALSE);
571 return get_contents_win32 (filename, contents, length, error);
573 return get_contents_posix (filename, contents, length, error);
578 * mkstemp() implementation is from the GNU C library.
579 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
583 * @tmpl: template filename
585 * Opens a temporary file. See the <function>mkstemp()</function> documentation
586 * on most UNIX-like systems. This is a portability wrapper, which simply calls
587 * <function>mkstemp()</function> on systems that have it, and implements
588 * it in GLib otherwise.
590 * The parameter is a string that should match the rules for
591 * <function>mkstemp()</function>, i.e. end in "XXXXXX". The X string will
592 * be modified to form the name of a file that didn't exist.
594 * Return value: A file handle (as from <function>open()</function>) to the file
595 * opened for reading and writing. The file is opened in binary mode
596 * on platforms where there is a difference. The file handle should be
597 * closed with <function>close()</function>. In case of errors, -1 is returned.
600 g_mkstemp (char *tmpl)
603 return mkstemp (tmpl);
608 static const char letters[] =
609 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
610 static const int NLETTERS = sizeof (letters) - 1;
613 static int counter = 0;
616 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
619 /* This is where the Xs start. */
620 XXXXXX = &tmpl[len - 6];
622 /* Get some more or less random data. */
623 g_get_current_time (&tv);
624 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
626 for (count = 0; count < 100; value += 7777, ++count)
630 /* Fill in the random bits. */
631 XXXXXX[0] = letters[v % NLETTERS];
633 XXXXXX[1] = letters[v % NLETTERS];
635 XXXXXX[2] = letters[v % NLETTERS];
637 XXXXXX[3] = letters[v % NLETTERS];
639 XXXXXX[4] = letters[v % NLETTERS];
641 XXXXXX[5] = letters[v % NLETTERS];
643 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
647 else if (errno != EEXIST)
648 /* Any other error will apply also to other names we might
649 * try, and there are 2^32 or so of them, so give up now.
654 /* We got out of the loop because we ran out of combinations to try. */
661 * @tmpl: Template for file name, as in g_mkstemp(), basename only
662 * @name_used: location to store actual name used
663 * @error: return location for a #GError
665 * Opens a file for writing in the preferred directory for temporary
666 * files (as returned by g_get_tmp_dir()).
668 * @tmpl should be a string ending with six 'X' characters, as the
669 * parameter to g_mkstemp() (or <function>mkstemp()</function>).
670 * However, unlike these functions, the template should only be a
671 * basename, no directory components are allowed. If template is %NULL,
672 * a default template is used.
674 * Note that in contrast to g_mkstemp() (and <function>mkstemp()</function>)
675 * @tmpl is not modified, and might thus be a read-only literal string.
677 * The actual name used is returned in @name_used if non-%NULL. This
678 * string should be freed with g_free() when not needed any longer.
680 * Return value: A file handle (as from <function>open()</function>) to
681 * the file opened for reading and writing. The file is opened in binary
682 * mode on platforms where there is a difference. The file handle should be
683 * closed with <function>close()</function>. In case of errors, -1 is returned
684 * and @error will be set.
687 g_file_open_tmp (const char *tmpl,
699 if (strchr (tmpl, G_DIR_SEPARATOR)
701 || strchr (tmpl, '/')
708 _("Template '%s' invalid, should not contain a '%s'"),
709 tmpl, G_DIR_SEPARATOR_S);
714 if (strlen (tmpl) < 6 ||
715 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
720 _("Template '%s' doesn't end with XXXXXX"),
725 tmpdir = g_get_tmp_dir ();
727 if (tmpdir [strlen (tmpdir) - 1] == G_DIR_SEPARATOR)
730 sep = G_DIR_SEPARATOR_S;
732 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
734 retval = g_mkstemp (fulltemplate);
740 g_file_error_from_errno (errno),
741 _("Failed to create file '%s': %s"),
742 fulltemplate, strerror (errno));
743 g_free (fulltemplate);
748 *name_used = fulltemplate;
750 g_free (fulltemplate);
756 g_build_pathv (const gchar *separator,
757 const gchar *first_element,
761 gint separator_len = strlen (separator);
762 gboolean is_first = TRUE;
763 const gchar *next_element;
765 result = g_string_new (NULL);
767 next_element = first_element;
771 const gchar *element;
777 element = next_element;
778 next_element = va_arg (args, gchar *);
787 else if (separator_len)
790 strncmp (start, separator, separator_len) == 0)
791 start += separator_len;
794 end = start + strlen (start);
796 if (next_element && separator_len)
798 while (end > start + separator_len &&
799 strncmp (end - separator_len, separator, separator_len) == 0)
800 end -= separator_len;
806 g_string_append (result, separator);
808 g_string_append_len (result, start, end - start);
812 return g_string_free (result, FALSE);
817 * @separator: a string used to separator the elements of the path.
818 * @first_element: the first element in the path
819 * @Varargs: remaining elements in path
821 * Creates a path from a series of elements using @separator as the
822 * separator between elements. At the boundary between two elements,
823 * any trailing occurrences of separator in the first element, or
824 * leading occurrences of separator in the second element are removed
825 * and exactly one copy of the separator is inserted.
827 * Return value: a newly-allocated string that must be freed with g_free().
830 g_build_path (const gchar *separator,
831 const gchar *first_element,
837 g_return_val_if_fail (separator != NULL, NULL);
839 va_start (args, first_element);
840 str = g_build_pathv (separator, first_element, args);
848 * @first_element: the first element in the path
849 * @Varargs: remaining elements in path
851 * Creates a filename from a series of elements using the correct
852 * separator for filenames. This function behaves identically
853 * to <literal>g_build_path (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
855 * No attempt is made to force the resulting filename to be an absolute
856 * path. If the first element is a relative path, the result will
857 * be a relative path.
859 * Return value: a newly-allocated string that must be freed with g_free().
862 g_build_filename (const gchar *first_element,
868 va_start (args, first_element);
869 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);