Add a testcase for the previous fix.
[glib.git] / glib / gfileutils.c
blob10e5edeec6f7fad6dfa0fc0df404ba419ade2133
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.
21 #include "config.h"
23 #include "galias.h"
24 #include "glib.h"
26 #include <sys/stat.h>
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <string.h>
34 #include <errno.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <fcntl.h>
38 #include <stdlib.h>
40 #ifdef G_OS_WIN32
41 #include <io.h>
42 #ifndef F_OK
43 #define F_OK 0
44 #define W_OK 2
45 #define R_OK 4
46 #endif /* !F_OK */
48 #ifndef S_ISREG
49 #define S_ISREG(mode) ((mode)&_S_IFREG)
50 #endif
52 #ifndef S_ISDIR
53 #define S_ISDIR(mode) ((mode)&_S_IFDIR)
54 #endif
56 #endif /* G_OS_WIN32 */
58 #ifndef S_ISLNK
59 #define S_ISLNK(x) 0
60 #endif
62 #ifndef O_BINARY
63 #define O_BINARY 0
64 #endif
66 #include "gstdio.h"
67 #include "glibintl.h"
69 /**
70 * g_file_test:
71 * @filename: a filename to test
72 * @test: bitfield of #GFileTest flags
74 * Returns %TRUE if any of the tests in the bitfield @test are
75 * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS |
76 * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists;
77 * the check whether it's a directory doesn't matter since the existence
78 * test is %TRUE. With the current set of available tests, there's no point
79 * passing in more than one test at a time.
81 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
82 * so for a symbolic link to a regular file g_file_test() will return
83 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
85 * Note, that for a dangling symbolic link g_file_test() will return
86 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
88 * You should never use g_file_test() to test whether it is safe
89 * to perform an operaton, because there is always the possibility
90 * of the condition changing before you actually perform the operation.
91 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
92 * to know whether it is is safe to write to a file without being
93 * tricked into writing into a different location. It doesn't work!
95 * <informalexample><programlisting>
96 * /&ast; DON'T DO THIS &ast;/
97 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) {
98 * fd = g_open (filename, O_WRONLY);
99 * /&ast; write to fd &ast;/
101 * </programlisting></informalexample>
103 * Another thing to note is that %G_FILE_TEST_EXISTS and
104 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
105 * system call. This usually doesn't matter, but if your program
106 * is setuid or setgid it means that these tests will give you
107 * the answer for the real user ID and group ID , rather than the
108 * effective user ID and group ID.
110 * Return value: whether a test was %TRUE
112 gboolean
113 g_file_test (const gchar *filename,
114 GFileTest test)
116 #ifdef G_OS_WIN32
117 if (G_WIN32_HAVE_WIDECHAR_API ())
119 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
121 if (wfilename == NULL)
122 return FALSE;
124 if ((test & G_FILE_TEST_EXISTS) && (_waccess (wfilename, F_OK) == 0))
126 g_free (wfilename);
127 return TRUE;
130 if (test & (G_FILE_TEST_IS_REGULAR |
131 G_FILE_TEST_IS_DIR |
132 G_FILE_TEST_IS_EXECUTABLE))
134 struct _stat s;
136 if (_wstat (wfilename, &s) == 0)
138 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
140 g_free (wfilename);
141 return TRUE;
144 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
146 g_free (wfilename);
147 return TRUE;
150 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
151 (s.st_mode & _S_IEXEC))
153 g_free (wfilename);
154 return TRUE;
159 g_free (wfilename);
161 return FALSE;
163 else
165 gchar *cp_filename = g_locale_from_utf8 (filename, -1, NULL, NULL, NULL);
167 if (cp_filename == NULL)
168 return FALSE;
170 if ((test & G_FILE_TEST_EXISTS) && (access (cp_filename, F_OK) == 0))
172 g_free (cp_filename);
173 return TRUE;
176 if (test & (G_FILE_TEST_IS_REGULAR |
177 G_FILE_TEST_IS_DIR |
178 G_FILE_TEST_IS_EXECUTABLE))
180 struct stat s;
182 if (stat (cp_filename, &s) == 0)
184 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
186 g_free (cp_filename);
187 return TRUE;
190 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
192 g_free (cp_filename);
193 return TRUE;
196 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
197 (s.st_mode & _S_IEXEC))
199 g_free (cp_filename);
200 return TRUE;
205 g_free (cp_filename);
207 return FALSE;
209 #else
210 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
211 return TRUE;
213 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
215 if (getuid () != 0)
216 return TRUE;
218 /* For root, on some POSIX systems, access (filename, X_OK)
219 * will succeed even if no executable bits are set on the
220 * file. We fall through to a stat test to avoid that.
223 else
224 test &= ~G_FILE_TEST_IS_EXECUTABLE;
226 if (test & G_FILE_TEST_IS_SYMLINK)
228 struct stat s;
230 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
231 return TRUE;
234 if (test & (G_FILE_TEST_IS_REGULAR |
235 G_FILE_TEST_IS_DIR |
236 G_FILE_TEST_IS_EXECUTABLE))
238 struct stat s;
240 if (stat (filename, &s) == 0)
242 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
243 return TRUE;
245 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
246 return TRUE;
248 /* The extra test for root when access (file, X_OK) succeeds.
250 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
251 ((s.st_mode & S_IXOTH) ||
252 (s.st_mode & S_IXUSR) ||
253 (s.st_mode & S_IXGRP)))
254 return TRUE;
258 return FALSE;
259 #endif
262 #ifdef G_OS_WIN32
264 #undef g_file_test
266 /* Binary compatibility version. Not for newly compiled code. */
268 gboolean
269 g_file_test (const gchar *filename,
270 GFileTest test)
272 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
273 gboolean retval;
275 if (utf8_filename == NULL)
276 return FALSE;
278 retval = g_file_test_utf8 (utf8_filename, test);
280 g_free (utf8_filename);
282 return retval;
285 #endif
287 GQuark
288 g_file_error_quark (void)
290 static GQuark q = 0;
291 if (q == 0)
292 q = g_quark_from_static_string ("g-file-error-quark");
294 return q;
298 * g_file_error_from_errno:
299 * @err_no: an "errno" value
301 * Gets a #GFileError constant based on the passed-in @errno.
302 * For example, if you pass in %EEXIST this function returns
303 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
304 * assume that all #GFileError values will exist.
306 * Normally a #GFileError value goes into a #GError returned
307 * from a function that manipulates files. So you would use
308 * g_file_error_from_errno() when constructing a #GError.
310 * Return value: #GFileError corresponding to the given @errno
312 GFileError
313 g_file_error_from_errno (gint err_no)
315 switch (err_no)
317 #ifdef EEXIST
318 case EEXIST:
319 return G_FILE_ERROR_EXIST;
320 break;
321 #endif
323 #ifdef EISDIR
324 case EISDIR:
325 return G_FILE_ERROR_ISDIR;
326 break;
327 #endif
329 #ifdef EACCES
330 case EACCES:
331 return G_FILE_ERROR_ACCES;
332 break;
333 #endif
335 #ifdef ENAMETOOLONG
336 case ENAMETOOLONG:
337 return G_FILE_ERROR_NAMETOOLONG;
338 break;
339 #endif
341 #ifdef ENOENT
342 case ENOENT:
343 return G_FILE_ERROR_NOENT;
344 break;
345 #endif
347 #ifdef ENOTDIR
348 case ENOTDIR:
349 return G_FILE_ERROR_NOTDIR;
350 break;
351 #endif
353 #ifdef ENXIO
354 case ENXIO:
355 return G_FILE_ERROR_NXIO;
356 break;
357 #endif
359 #ifdef ENODEV
360 case ENODEV:
361 return G_FILE_ERROR_NODEV;
362 break;
363 #endif
365 #ifdef EROFS
366 case EROFS:
367 return G_FILE_ERROR_ROFS;
368 break;
369 #endif
371 #ifdef ETXTBSY
372 case ETXTBSY:
373 return G_FILE_ERROR_TXTBSY;
374 break;
375 #endif
377 #ifdef EFAULT
378 case EFAULT:
379 return G_FILE_ERROR_FAULT;
380 break;
381 #endif
383 #ifdef ELOOP
384 case ELOOP:
385 return G_FILE_ERROR_LOOP;
386 break;
387 #endif
389 #ifdef ENOSPC
390 case ENOSPC:
391 return G_FILE_ERROR_NOSPC;
392 break;
393 #endif
395 #ifdef ENOMEM
396 case ENOMEM:
397 return G_FILE_ERROR_NOMEM;
398 break;
399 #endif
401 #ifdef EMFILE
402 case EMFILE:
403 return G_FILE_ERROR_MFILE;
404 break;
405 #endif
407 #ifdef ENFILE
408 case ENFILE:
409 return G_FILE_ERROR_NFILE;
410 break;
411 #endif
413 #ifdef EBADF
414 case EBADF:
415 return G_FILE_ERROR_BADF;
416 break;
417 #endif
419 #ifdef EINVAL
420 case EINVAL:
421 return G_FILE_ERROR_INVAL;
422 break;
423 #endif
425 #ifdef EPIPE
426 case EPIPE:
427 return G_FILE_ERROR_PIPE;
428 break;
429 #endif
431 #ifdef EAGAIN
432 case EAGAIN:
433 return G_FILE_ERROR_AGAIN;
434 break;
435 #endif
437 #ifdef EINTR
438 case EINTR:
439 return G_FILE_ERROR_INTR;
440 break;
441 #endif
443 #ifdef EIO
444 case EIO:
445 return G_FILE_ERROR_IO;
446 break;
447 #endif
449 #ifdef EPERM
450 case EPERM:
451 return G_FILE_ERROR_PERM;
452 break;
453 #endif
455 #ifdef ENOSYS
456 case ENOSYS:
457 return G_FILE_ERROR_NOSYS;
458 break;
459 #endif
461 default:
462 return G_FILE_ERROR_FAILED;
463 break;
467 static gboolean
468 get_contents_stdio (const gchar *display_filename,
469 FILE *f,
470 gchar **contents,
471 gsize *length,
472 GError **error)
474 gchar buf[2048];
475 size_t bytes;
476 char *str;
477 size_t total_bytes;
478 size_t total_allocated;
480 g_assert (f != NULL);
482 #define STARTING_ALLOC 64
484 total_bytes = 0;
485 total_allocated = STARTING_ALLOC;
486 str = g_malloc (STARTING_ALLOC);
488 while (!feof (f))
490 bytes = fread (buf, 1, 2048, f);
492 while ((total_bytes + bytes + 1) > total_allocated)
494 total_allocated *= 2;
495 str = g_try_realloc (str, total_allocated);
497 if (str == NULL)
499 g_set_error (error,
500 G_FILE_ERROR,
501 G_FILE_ERROR_NOMEM,
502 _("Could not allocate %lu bytes to read file \"%s\""),
503 (gulong) total_allocated,
504 display_filename);
506 goto error;
510 if (ferror (f))
512 g_set_error (error,
513 G_FILE_ERROR,
514 g_file_error_from_errno (errno),
515 _("Error reading file '%s': %s"),
516 display_filename,
517 g_strerror (errno));
519 goto error;
522 memcpy (str + total_bytes, buf, bytes);
523 total_bytes += bytes;
526 fclose (f);
528 str[total_bytes] = '\0';
530 if (length)
531 *length = total_bytes;
533 *contents = str;
535 return TRUE;
537 error:
539 g_free (str);
540 fclose (f);
542 return FALSE;
545 #ifndef G_OS_WIN32
547 static gboolean
548 get_contents_regfile (const gchar *display_filename,
549 struct stat *stat_buf,
550 gint fd,
551 gchar **contents,
552 gsize *length,
553 GError **error)
555 gchar *buf;
556 size_t bytes_read;
557 size_t size;
558 size_t alloc_size;
560 size = stat_buf->st_size;
562 alloc_size = size + 1;
563 buf = g_try_malloc (alloc_size);
565 if (buf == NULL)
567 g_set_error (error,
568 G_FILE_ERROR,
569 G_FILE_ERROR_NOMEM,
570 _("Could not allocate %lu bytes to read file \"%s\""),
571 (gulong) alloc_size,
572 display_filename);
574 goto error;
577 bytes_read = 0;
578 while (bytes_read < size)
580 gssize rc;
582 rc = read (fd, buf + bytes_read, size - bytes_read);
584 if (rc < 0)
586 if (errno != EINTR)
588 g_free (buf);
589 g_set_error (error,
590 G_FILE_ERROR,
591 g_file_error_from_errno (errno),
592 _("Failed to read from file '%s': %s"),
593 display_filename,
594 g_strerror (errno));
596 goto error;
599 else if (rc == 0)
600 break;
601 else
602 bytes_read += rc;
605 buf[bytes_read] = '\0';
607 if (length)
608 *length = bytes_read;
610 *contents = buf;
612 close (fd);
614 return TRUE;
616 error:
618 close (fd);
620 return FALSE;
623 static gboolean
624 get_contents_posix (const gchar *filename,
625 gchar **contents,
626 gsize *length,
627 GError **error)
629 struct stat stat_buf;
630 gint fd;
631 gchar *display_filename = g_filename_display_name (filename);
633 /* O_BINARY useful on Cygwin */
634 fd = open (filename, O_RDONLY|O_BINARY);
636 if (fd < 0)
638 g_set_error (error,
639 G_FILE_ERROR,
640 g_file_error_from_errno (errno),
641 _("Failed to open file '%s': %s"),
642 display_filename,
643 g_strerror (errno));
644 g_free (display_filename);
646 return FALSE;
649 /* I don't think this will ever fail, aside from ENOMEM, but. */
650 if (fstat (fd, &stat_buf) < 0)
652 close (fd);
653 g_set_error (error,
654 G_FILE_ERROR,
655 g_file_error_from_errno (errno),
656 _("Failed to get attributes of file '%s': fstat() failed: %s"),
657 display_filename,
658 g_strerror (errno));
659 g_free (display_filename);
661 return FALSE;
664 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
666 gboolean retval = get_contents_regfile (display_filename,
667 &stat_buf,
669 contents,
670 length,
671 error);
672 g_free (display_filename);
674 return retval;
676 else
678 FILE *f;
679 gboolean retval;
681 f = fdopen (fd, "r");
683 if (f == NULL)
685 g_set_error (error,
686 G_FILE_ERROR,
687 g_file_error_from_errno (errno),
688 _("Failed to open file '%s': fdopen() failed: %s"),
689 display_filename,
690 g_strerror (errno));
691 g_free (display_filename);
693 return FALSE;
696 retval = get_contents_stdio (display_filename, f, contents, length, error);
697 g_free (display_filename);
699 return retval;
703 #else /* G_OS_WIN32 */
705 static gboolean
706 get_contents_win32 (const gchar *filename,
707 gchar **contents,
708 gsize *length,
709 GError **error)
711 FILE *f;
712 gboolean retval;
713 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
714 gchar *display_filename = g_filename_display_name (filename);
716 f = _wfopen (wfilename, L"rb");
717 g_free (wfilename);
719 if (f == NULL)
721 g_set_error (error,
722 G_FILE_ERROR,
723 g_file_error_from_errno (errno),
724 _("Failed to open file '%s': %s"),
725 display_filename,
726 g_strerror (errno));
727 g_free (display_filename);
729 return FALSE;
732 retval = get_contents_stdio (display_filename, f, contents, length, error);
733 g_free (display_filename);
735 return retval;
738 #endif
741 * g_file_get_contents:
742 * @filename: name of a file to read contents from, in the GLib file name encoding
743 * @contents: location to store an allocated string
744 * @length: location to store length in bytes of the contents
745 * @error: return location for a #GError
747 * Reads an entire file into allocated memory, with good error
748 * checking. If @error is set, %FALSE is returned, and @contents is set
749 * to %NULL. If %TRUE is returned, @error will not be set, and @contents
750 * will be set to the file contents. The string stored in @contents
751 * will be nul-terminated, so for text files you can pass %NULL for the
752 * @length argument. The error domain is #G_FILE_ERROR. Possible
753 * error codes are those in the #GFileError enumeration.
755 * Return value: %TRUE on success, %FALSE if error is set
757 gboolean
758 g_file_get_contents (const gchar *filename,
759 gchar **contents,
760 gsize *length,
761 GError **error)
763 g_return_val_if_fail (filename != NULL, FALSE);
764 g_return_val_if_fail (contents != NULL, FALSE);
766 *contents = NULL;
767 if (length)
768 *length = 0;
770 #ifdef G_OS_WIN32
771 return get_contents_win32 (filename, contents, length, error);
772 #else
773 return get_contents_posix (filename, contents, length, error);
774 #endif
777 #ifdef G_OS_WIN32
779 #undef g_file_get_contents
781 /* Binary compatibility version. Not for newly compiled code. */
783 gboolean
784 g_file_get_contents (const gchar *filename,
785 gchar **contents,
786 gsize *length,
787 GError **error)
789 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
790 gboolean retval;
792 if (utf8_filename == NULL)
793 return FALSE;
795 retval = g_file_get_contents (utf8_filename, contents, length, error);
797 g_free (utf8_filename);
799 return retval;
802 #endif
805 * mkstemp() implementation is from the GNU C library.
806 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
809 * g_mkstemp:
810 * @tmpl: template filename
812 * Opens a temporary file. See the mkstemp() documentation
813 * on most UNIX-like systems. This is a portability wrapper, which simply calls
814 * mkstemp() on systems that have it, and implements
815 * it in GLib otherwise.
817 * The parameter is a string that should match the rules for
818 * mkstemp(), i.e. end in "XXXXXX". The X string will
819 * be modified to form the name of a file that didn't exist.
820 * The string should be in the GLib file name encoding. Most importantly,
821 * on Windows it should be in UTF-8.
823 * Return value: A file handle (as from open()) to the file
824 * opened for reading and writing. The file is opened in binary mode
825 * on platforms where there is a difference. The file handle should be
826 * closed with close(). In case of errors, -1 is returned.
828 gint
829 g_mkstemp (gchar *tmpl)
831 #ifdef HAVE_MKSTEMP
832 return mkstemp (tmpl);
833 #else
834 int len;
835 char *XXXXXX;
836 int count, fd;
837 static const char letters[] =
838 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
839 static const int NLETTERS = sizeof (letters) - 1;
840 glong value;
841 GTimeVal tv;
842 static int counter = 0;
844 len = strlen (tmpl);
845 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
846 return -1;
848 /* This is where the Xs start. */
849 XXXXXX = &tmpl[len - 6];
851 /* Get some more or less random data. */
852 g_get_current_time (&tv);
853 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
855 for (count = 0; count < 100; value += 7777, ++count)
857 glong v = value;
859 /* Fill in the random bits. */
860 XXXXXX[0] = letters[v % NLETTERS];
861 v /= NLETTERS;
862 XXXXXX[1] = letters[v % NLETTERS];
863 v /= NLETTERS;
864 XXXXXX[2] = letters[v % NLETTERS];
865 v /= NLETTERS;
866 XXXXXX[3] = letters[v % NLETTERS];
867 v /= NLETTERS;
868 XXXXXX[4] = letters[v % NLETTERS];
869 v /= NLETTERS;
870 XXXXXX[5] = letters[v % NLETTERS];
872 /* tmpl is in UTF-8 on Windows, thus use g_open() */
873 fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
875 if (fd >= 0)
876 return fd;
877 else if (errno != EEXIST)
878 /* Any other error will apply also to other names we might
879 * try, and there are 2^32 or so of them, so give up now.
881 return -1;
884 /* We got out of the loop because we ran out of combinations to try. */
885 return -1;
886 #endif
889 #ifdef G_OS_WIN32
891 #undef g_mkstemp
893 /* Binary compatibility version. Not for newly compiled code. */
895 gint
896 g_mkstemp (gchar *tmpl)
898 int len;
899 char *XXXXXX;
900 int count, fd;
901 static const char letters[] =
902 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
903 static const int NLETTERS = sizeof (letters) - 1;
904 glong value;
905 GTimeVal tv;
906 static int counter = 0;
908 len = strlen (tmpl);
909 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
910 return -1;
912 /* This is where the Xs start. */
913 XXXXXX = &tmpl[len - 6];
915 /* Get some more or less random data. */
916 g_get_current_time (&tv);
917 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
919 for (count = 0; count < 100; value += 7777, ++count)
921 glong v = value;
923 /* Fill in the random bits. */
924 XXXXXX[0] = letters[v % NLETTERS];
925 v /= NLETTERS;
926 XXXXXX[1] = letters[v % NLETTERS];
927 v /= NLETTERS;
928 XXXXXX[2] = letters[v % NLETTERS];
929 v /= NLETTERS;
930 XXXXXX[3] = letters[v % NLETTERS];
931 v /= NLETTERS;
932 XXXXXX[4] = letters[v % NLETTERS];
933 v /= NLETTERS;
934 XXXXXX[5] = letters[v % NLETTERS];
936 /* This is the backward compatibility system codepage version,
937 * thus use normal open().
939 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
941 if (fd >= 0)
942 return fd;
943 else if (errno != EEXIST)
944 /* Any other error will apply also to other names we might
945 * try, and there are 2^32 or so of them, so give up now.
947 return -1;
950 /* We got out of the loop because we ran out of combinations to try. */
951 return -1;
954 #endif
957 * g_file_open_tmp:
958 * @tmpl: Template for file name, as in g_mkstemp(), basename only
959 * @name_used: location to store actual name used
960 * @error: return location for a #GError
962 * Opens a file for writing in the preferred directory for temporary
963 * files (as returned by g_get_tmp_dir()).
965 * @tmpl should be a string in the GLib file name encoding ending with
966 * six 'X' characters, as the parameter to g_mkstemp() (or mkstemp()).
967 * However, unlike these functions, the template should only be a
968 * basename, no directory components are allowed. If template is
969 * %NULL, a default template is used.
971 * Note that in contrast to g_mkstemp() (and mkstemp())
972 * @tmpl is not modified, and might thus be a read-only literal string.
974 * The actual name used is returned in @name_used if non-%NULL. This
975 * string should be freed with g_free() when not needed any longer.
976 * The returned name is in the GLib file name encoding.
978 * Return value: A file handle (as from open()) to
979 * the file opened for reading and writing. The file is opened in binary
980 * mode on platforms where there is a difference. The file handle should be
981 * closed with close(). In case of errors, -1 is returned
982 * and @error will be set.
984 gint
985 g_file_open_tmp (const gchar *tmpl,
986 gchar **name_used,
987 GError **error)
989 int retval;
990 const char *tmpdir;
991 char *sep;
992 char *fulltemplate;
993 const char *slash;
995 if (tmpl == NULL)
996 tmpl = ".XXXXXX";
998 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
999 #ifdef G_OS_WIN32
1000 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1001 #endif
1004 gchar *display_tmpl = g_filename_display_name (tmpl);
1005 char c[2];
1006 c[0] = *slash;
1007 c[1] = '\0';
1009 g_set_error (error,
1010 G_FILE_ERROR,
1011 G_FILE_ERROR_FAILED,
1012 _("Template '%s' invalid, should not contain a '%s'"),
1013 display_tmpl, c);
1014 g_free (display_tmpl);
1016 return -1;
1019 if (strlen (tmpl) < 6 ||
1020 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
1022 gchar *display_tmpl = g_filename_display_name (tmpl);
1023 g_set_error (error,
1024 G_FILE_ERROR,
1025 G_FILE_ERROR_FAILED,
1026 _("Template '%s' doesn't end with XXXXXX"),
1027 display_tmpl);
1028 g_free (display_tmpl);
1029 return -1;
1032 tmpdir = g_get_tmp_dir ();
1034 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1035 sep = "";
1036 else
1037 sep = G_DIR_SEPARATOR_S;
1039 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1041 retval = g_mkstemp (fulltemplate);
1043 if (retval == -1)
1045 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1046 g_set_error (error,
1047 G_FILE_ERROR,
1048 g_file_error_from_errno (errno),
1049 _("Failed to create file '%s': %s"),
1050 display_fulltemplate, g_strerror (errno));
1051 g_free (display_fulltemplate);
1052 g_free (fulltemplate);
1053 return -1;
1056 if (name_used)
1057 *name_used = fulltemplate;
1058 else
1059 g_free (fulltemplate);
1061 return retval;
1064 #ifdef G_OS_WIN32
1066 #undef g_file_open_tmp
1068 /* Binary compatibility version. Not for newly compiled code. */
1070 gint
1071 g_file_open_tmp (const gchar *tmpl,
1072 gchar **name_used,
1073 GError **error)
1075 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1076 gchar *utf8_name_used;
1077 gint retval;
1079 if (utf8_tmpl == NULL)
1080 return -1;
1082 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1084 if (retval == -1)
1085 return -1;
1087 if (name_used)
1088 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1090 g_free (utf8_name_used);
1092 return retval;
1095 #endif
1097 static gchar *
1098 g_build_pathv (const gchar *separator,
1099 const gchar *first_element,
1100 va_list args)
1102 GString *result;
1103 gint separator_len = strlen (separator);
1104 gboolean is_first = TRUE;
1105 gboolean have_leading = FALSE;
1106 const gchar *single_element = NULL;
1107 const gchar *next_element;
1108 const gchar *last_trailing = NULL;
1110 result = g_string_new (NULL);
1112 next_element = first_element;
1114 while (TRUE)
1116 const gchar *element;
1117 const gchar *start;
1118 const gchar *end;
1120 if (next_element)
1122 element = next_element;
1123 next_element = va_arg (args, gchar *);
1125 else
1126 break;
1128 /* Ignore empty elements */
1129 if (!*element)
1130 continue;
1132 start = element;
1134 if (separator_len)
1136 while (start &&
1137 strncmp (start, separator, separator_len) == 0)
1138 start += separator_len;
1141 end = start + strlen (start);
1143 if (separator_len)
1145 while (end >= start + separator_len &&
1146 strncmp (end - separator_len, separator, separator_len) == 0)
1147 end -= separator_len;
1149 last_trailing = end;
1150 while (last_trailing >= element + separator_len &&
1151 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1152 last_trailing -= separator_len;
1154 if (!have_leading)
1156 /* If the leading and trailing separator strings are in the
1157 * same element and overlap, the result is exactly that element
1159 if (last_trailing <= start)
1160 single_element = element;
1162 g_string_append_len (result, element, start - element);
1163 have_leading = TRUE;
1165 else
1166 single_element = NULL;
1169 if (end == start)
1170 continue;
1172 if (!is_first)
1173 g_string_append (result, separator);
1175 g_string_append_len (result, start, end - start);
1176 is_first = FALSE;
1179 if (single_element)
1181 g_string_free (result, TRUE);
1182 return g_strdup (single_element);
1184 else
1186 if (last_trailing)
1187 g_string_append (result, last_trailing);
1189 return g_string_free (result, FALSE);
1194 * g_build_path:
1195 * @separator: a string used to separator the elements of the path.
1196 * @first_element: the first element in the path
1197 * @Varargs: remaining elements in path, terminated by %NULL
1199 * Creates a path from a series of elements using @separator as the
1200 * separator between elements. At the boundary between two elements,
1201 * any trailing occurrences of separator in the first element, or
1202 * leading occurrences of separator in the second element are removed
1203 * and exactly one copy of the separator is inserted.
1205 * Empty elements are ignored.
1207 * The number of leading copies of the separator on the result is
1208 * the same as the number of leading copies of the separator on
1209 * the first non-empty element.
1211 * The number of trailing copies of the separator on the result is
1212 * the same as the number of trailing copies of the separator on
1213 * the last non-empty element. (Determination of the number of
1214 * trailing copies is done without stripping leading copies, so
1215 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1216 * has 1 trailing copy.)
1218 * However, if there is only a single non-empty element, and there
1219 * are no characters in that element not part of the leading or
1220 * trailing separators, then the result is exactly the original value
1221 * of that element.
1223 * Other than for determination of the number of leading and trailing
1224 * copies of the separator, elements consisting only of copies
1225 * of the separator are ignored.
1227 * Return value: a newly-allocated string that must be freed with g_free().
1229 gchar *
1230 g_build_path (const gchar *separator,
1231 const gchar *first_element,
1232 ...)
1234 gchar *str;
1235 va_list args;
1237 g_return_val_if_fail (separator != NULL, NULL);
1239 va_start (args, first_element);
1240 str = g_build_pathv (separator, first_element, args);
1241 va_end (args);
1243 return str;
1247 * g_build_filename:
1248 * @first_element: the first element in the path
1249 * @Varargs: remaining elements in path, terminated by %NULL
1251 * Creates a filename from a series of elements using the correct
1252 * separator for filenames.
1254 * On Unix, this function behaves identically to <literal>g_build_path
1255 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1257 * On Windows, it takes into account that either the backslash
1258 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1259 * as separator in filenames, but otherwise behaves as on Unix. When
1260 * file pathname separators need to be inserted, the one that last
1261 * previously occurred in the parameters (reading from left to right)
1262 * is used.
1264 * No attempt is made to force the resulting filename to be an absolute
1265 * path. If the first element is a relative path, the result will
1266 * be a relative path.
1268 * Return value: a newly-allocated string that must be freed with g_free().
1270 gchar *
1271 g_build_filename (const gchar *first_element,
1272 ...)
1274 #ifndef G_OS_WIN32
1275 gchar *str;
1276 va_list args;
1278 va_start (args, first_element);
1279 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
1280 va_end (args);
1282 return str;
1283 #else
1284 /* Code copied from g_build_pathv(), and modifed to use two
1285 * alternative single-character separators.
1287 va_list args;
1288 GString *result;
1289 gboolean is_first = TRUE;
1290 gboolean have_leading = FALSE;
1291 const gchar *single_element = NULL;
1292 const gchar *next_element;
1293 const gchar *last_trailing = NULL;
1294 gchar current_separator = '\\';
1296 va_start (args, first_element);
1298 result = g_string_new (NULL);
1300 next_element = first_element;
1302 while (TRUE)
1304 const gchar *element;
1305 const gchar *start;
1306 const gchar *end;
1308 if (next_element)
1310 element = next_element;
1311 next_element = va_arg (args, gchar *);
1313 else
1314 break;
1316 /* Ignore empty elements */
1317 if (!*element)
1318 continue;
1320 start = element;
1322 if (TRUE)
1324 while (start &&
1325 (*start == '\\' || *start == '/'))
1327 current_separator = *start;
1328 start++;
1332 end = start + strlen (start);
1334 if (TRUE)
1336 while (end >= start + 1 &&
1337 (end[-1] == '\\' || end[-1] == '/'))
1339 current_separator = end[-1];
1340 end--;
1343 last_trailing = end;
1344 while (last_trailing >= element + 1 &&
1345 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1346 last_trailing--;
1348 if (!have_leading)
1350 /* If the leading and trailing separator strings are in the
1351 * same element and overlap, the result is exactly that element
1353 if (last_trailing <= start)
1354 single_element = element;
1356 g_string_append_len (result, element, start - element);
1357 have_leading = TRUE;
1359 else
1360 single_element = NULL;
1363 if (end == start)
1364 continue;
1366 if (!is_first)
1367 g_string_append_len (result, &current_separator, 1);
1369 g_string_append_len (result, start, end - start);
1370 is_first = FALSE;
1373 va_end (args);
1375 if (single_element)
1377 g_string_free (result, TRUE);
1378 return g_strdup (single_element);
1380 else
1382 if (last_trailing)
1383 g_string_append (result, last_trailing);
1385 return g_string_free (result, FALSE);
1387 #endif
1391 * g_file_read_link:
1392 * @filename: the symbolic link
1393 * @error: return location for a #GError
1395 * Reads the contents of the symbolic link @filename like the POSIX
1396 * readlink() function. The returned string is in the encoding used
1397 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1399 * Returns: A newly allocated string with the contents of the symbolic link,
1400 * or %NULL if an error occurred.
1402 * Since: 2.4
1404 gchar *
1405 g_file_read_link (const gchar *filename,
1406 GError **error)
1408 #ifdef HAVE_READLINK
1409 gchar *buffer;
1410 guint size;
1411 gint read_size;
1413 size = 256;
1414 buffer = g_malloc (size);
1416 while (TRUE)
1418 read_size = readlink (filename, buffer, size);
1419 if (read_size < 0) {
1420 gchar *display_filename = g_filename_display_name (filename);
1421 g_free (buffer);
1422 g_set_error (error,
1423 G_FILE_ERROR,
1424 g_file_error_from_errno (errno),
1425 _("Failed to read the symbolic link '%s': %s"),
1426 display_filename,
1427 g_strerror (errno));
1428 g_free (display_filename);
1430 return NULL;
1433 if (read_size < size)
1435 buffer[read_size] = 0;
1436 return buffer;
1439 size *= 2;
1440 buffer = g_realloc (buffer, size);
1442 #else
1443 g_set_error (error,
1444 G_FILE_ERROR,
1445 G_FILE_ERROR_INVAL,
1446 _("Symbolic links not supported"));
1448 return NULL;
1449 #endif