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.
33 #include <sys/types.h>
48 #define S_ISREG(mode) ((mode)&_S_IFREG)
52 #define S_ISDIR(mode) ((mode)&_S_IFDIR)
55 #endif /* G_OS_WIN32 */
69 * @filename: a filename to test
70 * @test: bitfield of #GFileTest flags
72 * Returns TRUE if any of the tests in the bitfield @test are
73 * TRUE. For example, (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)
74 * will return TRUE if the file exists; the check whether it's
75 * a directory doesn't matter since the existence test is TRUE.
76 * With the current set of available tests, there's no point
77 * passing in more than one test at a time.
79 * Return value: whether a test was TRUE
82 g_file_test (const gchar *filename,
85 if (test & G_FILE_TEST_EXISTS)
86 return (access (filename, F_OK) == 0);
87 else if (test & G_FILE_TEST_IS_EXECUTABLE)
88 return (access (filename, X_OK) == 0);
93 if (stat (filename, &s) < 0)
96 if ((test & G_FILE_TEST_IS_REGULAR) &&
99 else if ((test & G_FILE_TEST_IS_DIR) &&
102 else if ((test & G_FILE_TEST_IS_SYMLINK) &&
111 g_file_error_quark (void)
115 q = g_quark_from_static_string ("g-file-error-quark");
121 * g_file_error_from_errno:
122 * @err_no: an "errno" value
124 * Gets a #GFileError constant based on the passed-in errno.
125 * For example, if you pass in EEXIST this function returns
126 * #G_FILE_ERROR_EXIST. Unlike errno values, you can portably
127 * assume that all #GFileError values will exist.
129 * Normally a #GFileError value goes into a #GError returned
130 * from a function that manipulates files. So you would use
131 * g_file_error_from_errno() when constructing a #GError.
133 * Return value: #GFileError corresponding to the given errno
136 g_file_error_from_errno (gint err_no)
142 return G_FILE_ERROR_EXIST;
148 return G_FILE_ERROR_ISDIR;
154 return G_FILE_ERROR_ACCES;
160 return G_FILE_ERROR_NAMETOOLONG;
166 return G_FILE_ERROR_NOENT;
172 return G_FILE_ERROR_NOTDIR;
178 return G_FILE_ERROR_NXIO;
184 return G_FILE_ERROR_NODEV;
190 return G_FILE_ERROR_ROFS;
196 return G_FILE_ERROR_TXTBSY;
202 return G_FILE_ERROR_FAULT;
208 return G_FILE_ERROR_LOOP;
214 return G_FILE_ERROR_NOSPC;
220 return G_FILE_ERROR_NOMEM;
226 return G_FILE_ERROR_MFILE;
232 return G_FILE_ERROR_NFILE;
238 return G_FILE_ERROR_BADF;
244 return G_FILE_ERROR_INVAL;
250 return G_FILE_ERROR_PIPE;
256 return G_FILE_ERROR_AGAIN;
262 return G_FILE_ERROR_INTR;
268 return G_FILE_ERROR_IO;
274 return G_FILE_ERROR_PERM;
279 return G_FILE_ERROR_FAILED;
285 get_contents_stdio (const gchar *filename,
295 g_assert (f != NULL);
297 str = g_string_new ("");
301 bytes = fread (buf, 1, 2048, f);
307 g_file_error_from_errno (errno),
308 _("Error reading file '%s': %s"),
309 filename, strerror (errno));
311 g_string_free (str, TRUE);
316 g_string_append_len (str, buf, bytes);
324 *contents = g_string_free (str, FALSE);
332 get_contents_regfile (const gchar *filename,
333 struct stat *stat_buf,
343 size = stat_buf->st_size;
345 buf = g_new (gchar, size + 1);
348 while (bytes_read < size)
352 rc = read (fd, buf + bytes_read, size - bytes_read);
364 g_file_error_from_errno (errno),
365 _("Failed to read from file '%s': %s"),
366 filename, strerror (errno));
377 buf[bytes_read] = '\0';
380 *length = bytes_read;
388 get_contents_posix (const gchar *filename,
393 struct stat stat_buf;
396 /* O_BINARY useful on Cygwin */
397 fd = open (filename, O_RDONLY|O_BINARY);
403 g_file_error_from_errno (errno),
404 _("Failed to open file '%s': %s"),
405 filename, strerror (errno));
410 /* I don't think this will ever fail, aside from ENOMEM, but. */
411 if (fstat (fd, &stat_buf) < 0)
417 g_file_error_from_errno (errno),
418 _("Failed to get attributes of file '%s': fstat() failed: %s"),
419 filename, strerror (errno));
424 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
426 return get_contents_regfile (filename,
437 f = fdopen (fd, "r");
443 g_file_error_from_errno (errno),
444 _("Failed to open file '%s': fdopen() failed: %s"),
445 filename, strerror (errno));
450 return get_contents_stdio (filename, f, contents, length, error);
454 #else /* G_OS_WIN32 */
457 get_contents_win32 (const gchar *filename,
464 /* I guess you want binary mode; maybe you want text sometimes? */
465 f = fopen (filename, "rb");
471 g_file_error_from_errno (errno),
472 _("Failed to open file '%s': %s"),
473 filename, strerror (errno));
478 return get_contents_stdio (filename, f, contents, length, error);
484 * g_file_get_contents:
485 * @filename: a file to read contents from
486 * @contents: location to store an allocated string
487 * @length: location to store length in bytes of the contents
488 * @error: return location for a #GError
490 * Reads an entire file into allocated memory, with good error
491 * checking. If @error is set, FALSE is returned, and @contents is set
492 * to NULL. If TRUE is returned, @error will not be set, and @contents
493 * will be set to the file contents. The string stored in @contents
494 * will be nul-terminated, so for text files you can pass NULL for the
495 * @length argument. The error domain is #G_FILE_ERROR. Possible
496 * error codes are those in the #GFileError enumeration.
498 * FIXME currently crashes if the file is too big to fit in memory;
499 * should probably use g_try_malloc() when we have that function.
501 * Return value: TRUE on success, FALSE if error is set
504 g_file_get_contents (const gchar *filename,
509 g_return_val_if_fail (filename != NULL, FALSE);
510 g_return_val_if_fail (contents != NULL, FALSE);
517 return get_contents_win32 (filename, contents, length, error);
519 return get_contents_posix (filename, contents, length, error);
524 * mkstemp() implementation is from the GNU C library.
525 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
529 * @tmpl: template filename
531 * Open a temporary file. See "man mkstemp" on most UNIX-like systems.
532 * This is a portability wrapper, which simply calls mkstemp() on systems
533 * that have it, and implements it in GLib otherwise.
535 * The parameter is a string that should match the rules for mktemp, i.e.
536 * end in "XXXXXX". The X string will be modified to form the name
537 * of a file that didn't exist.
539 * Return value: A file handle (as from open()) to the file
540 * opened for reading and writing. The file is opened in binary mode
541 * on platforms where there is a difference. The file handle should be
542 * closed with close(). In case of errors, -1 is returned.
545 g_mkstemp (char *tmpl)
548 return mkstemp (tmpl);
553 static const char letters[] =
554 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
555 static const int NLETTERS = sizeof (letters) - 1;
558 static int counter = 0;
561 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
564 /* This is where the Xs start. */
565 XXXXXX = &tmpl[len - 6];
567 /* Get some more or less random data. */
568 g_get_current_time (&tv);
569 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
571 for (count = 0; count < 100; value += 7777, ++count)
575 /* Fill in the random bits. */
576 XXXXXX[0] = letters[v % NLETTERS];
578 XXXXXX[1] = letters[v % NLETTERS];
580 XXXXXX[2] = letters[v % NLETTERS];
582 XXXXXX[3] = letters[v % NLETTERS];
584 XXXXXX[4] = letters[v % NLETTERS];
586 XXXXXX[5] = letters[v % NLETTERS];
588 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
592 else if (errno != EEXIST)
593 /* Any other error will apply also to other names we might
594 * try, and there are 2^32 or so of them, so give up now.
599 /* We got out of the loop because we ran out of combinations to try. */
606 * @tmpl: Template for file name, as in g_mkstemp, basename only
607 * @name_used: location to store actual name used
608 * @error: return location for a #GError
610 * Opens a file for writing in the preferred directory for temporary
611 * files (as returned by g_get_tmp_dir()).
613 * @tmpl should be a string ending with six 'X' characters, as the
614 * parameter to g_mkstemp() (or mkstemp()). However, unlike these
615 * functions, the template should only be a basename, no directory
616 * components are allowed. If template is NULL, a default template is
619 * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
620 * modified, and might thus be a read-only literal string.
622 * The actual name used is returned in @name_used if non-NULL. This
623 * string should be freed with g_free when not needed any longer.
625 * Return value: A file handle (as from open()) to the file
626 * opened for reading and writing. The file is opened in binary mode
627 * on platforms where there is a difference. The file handle should be
628 * closed with close(). In case of errors, -1 is returned and
629 * @error will be set.
632 g_file_open_tmp (const char *tmpl,
644 if (strchr (tmpl, G_DIR_SEPARATOR)
646 || strchr (tmpl, '/')
653 _("Template '%s' illegal, should not contain a '%s'"),
654 tmpl, G_DIR_SEPARATOR_S);
659 if (strlen (tmpl) < 6 ||
660 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
665 _("Template '%s' doesn't end with XXXXXX"),
670 tmpdir = g_get_tmp_dir ();
672 if (tmpdir [strlen (tmpdir) - 1] == G_DIR_SEPARATOR)
675 sep = G_DIR_SEPARATOR_S;
677 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
679 retval = g_mkstemp (fulltemplate);
685 g_file_error_from_errno (errno),
686 _("Failed to create file '%s': %s"),
687 fulltemplate, strerror (errno));
688 g_free (fulltemplate);
693 *name_used = fulltemplate;
695 g_free (fulltemplate);