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);
317 g_string_append_len (str, buf, bytes);
325 *contents = g_string_free (str, FALSE);
333 get_contents_regfile (const gchar *filename,
334 struct stat *stat_buf,
344 size = stat_buf->st_size;
346 buf = g_new (gchar, size + 1);
349 while (bytes_read < size)
353 rc = read (fd, buf + bytes_read, size - bytes_read);
365 g_file_error_from_errno (errno),
366 _("Failed to read from file '%s': %s"),
367 filename, strerror (errno));
378 buf[bytes_read] = '\0';
381 *length = bytes_read;
389 get_contents_posix (const gchar *filename,
394 struct stat stat_buf;
397 /* O_BINARY useful on Cygwin */
398 fd = open (filename, O_RDONLY|O_BINARY);
404 g_file_error_from_errno (errno),
405 _("Failed to open file '%s': %s"),
406 filename, strerror (errno));
411 /* I don't think this will ever fail, aside from ENOMEM, but. */
412 if (fstat (fd, &stat_buf) < 0)
418 g_file_error_from_errno (errno),
419 _("Failed to get attributes of file '%s': fstat() failed: %s"),
420 filename, strerror (errno));
425 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
427 return get_contents_regfile (filename,
438 f = fdopen (fd, "r");
444 g_file_error_from_errno (errno),
445 _("Failed to open file '%s': fdopen() failed: %s"),
446 filename, strerror (errno));
451 return get_contents_stdio (filename, f, contents, length, error);
455 #else /* G_OS_WIN32 */
458 get_contents_win32 (const gchar *filename,
465 /* I guess you want binary mode; maybe you want text sometimes? */
466 f = fopen (filename, "rb");
472 g_file_error_from_errno (errno),
473 _("Failed to open file '%s': %s"),
474 filename, strerror (errno));
479 return get_contents_stdio (filename, f, contents, length, error);
485 * g_file_get_contents:
486 * @filename: a file to read contents from
487 * @contents: location to store an allocated string
488 * @length: location to store length in bytes of the contents
489 * @error: return location for a #GError
491 * Reads an entire file into allocated memory, with good error
492 * checking. If @error is set, FALSE is returned, and @contents is set
493 * to NULL. If TRUE is returned, @error will not be set, and @contents
494 * will be set to the file contents. The string stored in @contents
495 * will be nul-terminated, so for text files you can pass NULL for the
496 * @length argument. The error domain is #G_FILE_ERROR. Possible
497 * error codes are those in the #GFileError enumeration.
499 * FIXME currently crashes if the file is too big to fit in memory;
500 * should probably use g_try_malloc() when we have that function.
502 * Return value: TRUE on success, FALSE if error is set
505 g_file_get_contents (const gchar *filename,
510 g_return_val_if_fail (filename != NULL, FALSE);
511 g_return_val_if_fail (contents != NULL, FALSE);
518 return get_contents_win32 (filename, contents, length, error);
520 return get_contents_posix (filename, contents, length, error);
525 * mkstemp() implementation is from the GNU C library.
526 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
530 * @tmpl: template filename
532 * Open a temporary file. See "man mkstemp" on most UNIX-like systems.
533 * This is a portability wrapper, which simply calls mkstemp() on systems
534 * that have it, and implements it in GLib otherwise.
536 * The parameter is a string that should match the rules for mktemp, i.e.
537 * end in "XXXXXX". The X string will be modified to form the name
538 * of a file that didn't exist.
540 * Return value: A file handle (as from open()) to the file
541 * opened for reading and writing. The file is opened in binary mode
542 * on platforms where there is a difference. The file handle should be
543 * closed with close(). In case of errors, -1 is returned.
546 g_mkstemp (char *tmpl)
549 return mkstemp (tmpl);
554 static const char letters[] =
555 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
556 static const int NLETTERS = sizeof (letters) - 1;
559 static int counter = 0;
562 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
565 /* This is where the Xs start. */
566 XXXXXX = &tmpl[len - 6];
568 /* Get some more or less random data. */
569 g_get_current_time (&tv);
570 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
572 for (count = 0; count < 100; value += 7777, ++count)
576 /* Fill in the random bits. */
577 XXXXXX[0] = letters[v % NLETTERS];
579 XXXXXX[1] = letters[v % NLETTERS];
581 XXXXXX[2] = letters[v % NLETTERS];
583 XXXXXX[3] = letters[v % NLETTERS];
585 XXXXXX[4] = letters[v % NLETTERS];
587 XXXXXX[5] = letters[v % NLETTERS];
589 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
593 else if (errno != EEXIST)
594 /* Any other error will apply also to other names we might
595 * try, and there are 2^32 or so of them, so give up now.
600 /* We got out of the loop because we ran out of combinations to try. */
607 * @tmpl: Template for file name, as in g_mkstemp, basename only
608 * @name_used: location to store actual name used
609 * @error: return location for a #GError
611 * Opens a file for writing in the preferred directory for temporary
612 * files (as returned by g_get_tmp_dir()).
614 * @tmpl should be a string ending with six 'X' characters, as the
615 * parameter to g_mkstemp() (or mkstemp()). However, unlike these
616 * functions, the template should only be a basename, no directory
617 * components are allowed. If template is NULL, a default template is
620 * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
621 * modified, and might thus be a read-only literal string.
623 * The actual name used is returned in @name_used if non-NULL. This
624 * string should be freed with g_free when not needed any longer.
626 * Return value: A file handle (as from open()) to the file
627 * opened for reading and writing. The file is opened in binary mode
628 * on platforms where there is a difference. The file handle should be
629 * closed with close(). In case of errors, -1 is returned and
630 * @error will be set.
633 g_file_open_tmp (const char *tmpl,
645 if (strchr (tmpl, G_DIR_SEPARATOR)
647 || strchr (tmpl, '/')
654 _("Template '%s' illegal, should not contain a '%s'"),
655 tmpl, G_DIR_SEPARATOR_S);
660 if (strlen (tmpl) < 6 ||
661 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
666 _("Template '%s' doesn't end with XXXXXX"),
671 tmpdir = g_get_tmp_dir ();
673 if (tmpdir [strlen (tmpdir) - 1] == G_DIR_SEPARATOR)
676 sep = G_DIR_SEPARATOR_S;
678 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
680 retval = g_mkstemp (fulltemplate);
686 g_file_error_from_errno (errno),
687 _("Failed to create file '%s': %s"),
688 fulltemplate, strerror (errno));
689 g_free (fulltemplate);
694 *name_used = fulltemplate;
696 g_free (fulltemplate);