Avoid forcing extra newlines when using template files. (#171005)
[glib.git] / glib / gfileutils.c
blob05cd33e22fa1b96aa6124235a8520175112ebe38
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 "glib.h"
25 #include <sys/stat.h>
26 #ifdef HAVE_UNISTD_H
27 #include <unistd.h>
28 #endif
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <string.h>
33 #include <errno.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <fcntl.h>
37 #include <stdlib.h>
39 #ifdef G_OS_WIN32
40 #include <windows.h>
41 #include <io.h>
42 #endif /* G_OS_WIN32 */
44 #ifndef S_ISLNK
45 #define S_ISLNK(x) 0
46 #endif
48 #ifndef O_BINARY
49 #define O_BINARY 0
50 #endif
52 #include "gstdio.h"
53 #include "glibintl.h"
55 #include "galias.h"
57 /**
58 * g_file_test:
59 * @filename: a filename to test in the GLib file name encoding
60 * @test: bitfield of #GFileTest flags
62 * Returns %TRUE if any of the tests in the bitfield @test are
63 * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS |
64 * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists;
65 * the check whether it's a directory doesn't matter since the existence
66 * test is %TRUE. With the current set of available tests, there's no point
67 * passing in more than one test at a time.
69 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
70 * so for a symbolic link to a regular file g_file_test() will return
71 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
73 * Note, that for a dangling symbolic link g_file_test() will return
74 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
76 * You should never use g_file_test() to test whether it is safe
77 * to perform an operation, because there is always the possibility
78 * of the condition changing before you actually perform the operation.
79 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
80 * to know whether it is is safe to write to a file without being
81 * tricked into writing into a different location. It doesn't work!
83 * <informalexample><programlisting>
84 * /&ast; DON'T DO THIS &ast;/
85 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) {
86 * fd = g_open (filename, O_WRONLY);
87 * /&ast; write to fd &ast;/
88 * }
89 * </programlisting></informalexample>
91 * Another thing to note is that %G_FILE_TEST_EXISTS and
92 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
93 * system call. This usually doesn't matter, but if your program
94 * is setuid or setgid it means that these tests will give you
95 * the answer for the real user ID and group ID, rather than the
96 * effective user ID and group ID.
98 * On Windows, there are no symlinks, so testing for
99 * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
100 * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
101 * its name indicates that it is executable, checking for well-known
102 * extensions and those listed in the %PATHEXT environment variable.
104 * Return value: whether a test was %TRUE
106 gboolean
107 g_file_test (const gchar *filename,
108 GFileTest test)
110 #ifdef G_OS_WIN32
111 /* stuff missing in std vc6 api */
112 # ifndef INVALID_FILE_ATTRIBUTES
113 # define INVALID_FILE_ATTRIBUTES -1
114 # endif
115 # ifndef FILE_ATTRIBUTE_DEVICE
116 # define FILE_ATTRIBUTE_DEVICE 64
117 # endif
118 int attributes;
120 if (G_WIN32_HAVE_WIDECHAR_API ())
122 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
124 if (wfilename == NULL)
125 return FALSE;
127 attributes = GetFileAttributesW (wfilename);
129 g_free (wfilename);
131 else
133 gchar *cpfilename = g_locale_from_utf8 (filename, -1, NULL, NULL, NULL);
135 if (cpfilename == NULL)
136 return FALSE;
138 attributes = GetFileAttributesA (cpfilename);
140 g_free (cpfilename);
143 if (attributes == INVALID_FILE_ATTRIBUTES)
144 return FALSE;
146 if (test & G_FILE_TEST_EXISTS)
147 return TRUE;
149 if (test & G_FILE_TEST_IS_REGULAR)
150 return (attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0;
152 if (test & G_FILE_TEST_IS_DIR)
153 return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
155 if (test & G_FILE_TEST_IS_EXECUTABLE)
157 const gchar *lastdot = strrchr (filename, '.');
158 const gchar *pathext = NULL, *p;
159 int extlen;
161 if (lastdot == NULL)
162 return FALSE;
164 if (stricmp (lastdot, ".exe") == 0 ||
165 stricmp (lastdot, ".cmd") == 0 ||
166 stricmp (lastdot, ".bat") == 0 ||
167 stricmp (lastdot, ".com") == 0)
168 return TRUE;
170 /* Check if it is one of the types listed in %PATHEXT% */
172 pathext = g_getenv ("PATHEXT");
173 if (pathext == NULL)
174 return FALSE;
176 pathext = g_utf8_casefold (pathext, -1);
178 lastdot = g_utf8_casefold (lastdot, -1);
179 extlen = strlen (lastdot);
181 p = pathext;
182 while (TRUE)
184 const gchar *q = strchr (p, ';');
185 if (q == NULL)
186 q = p + strlen (p);
187 if (extlen == q - p &&
188 memcmp (lastdot, p, extlen) == 0)
190 g_free ((gchar *) pathext);
191 g_free ((gchar *) lastdot);
192 return TRUE;
194 if (*q)
195 p = q + 1;
196 else
197 break;
200 g_free ((gchar *) pathext);
201 g_free ((gchar *) lastdot);
202 return FALSE;
205 return FALSE;
206 #else
207 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
208 return TRUE;
210 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
212 if (getuid () != 0)
213 return TRUE;
215 /* For root, on some POSIX systems, access (filename, X_OK)
216 * will succeed even if no executable bits are set on the
217 * file. We fall through to a stat test to avoid that.
220 else
221 test &= ~G_FILE_TEST_IS_EXECUTABLE;
223 if (test & G_FILE_TEST_IS_SYMLINK)
225 struct stat s;
227 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
228 return TRUE;
231 if (test & (G_FILE_TEST_IS_REGULAR |
232 G_FILE_TEST_IS_DIR |
233 G_FILE_TEST_IS_EXECUTABLE))
235 struct stat s;
237 if (stat (filename, &s) == 0)
239 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
240 return TRUE;
242 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
243 return TRUE;
245 /* The extra test for root when access (file, X_OK) succeeds.
247 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
248 ((s.st_mode & S_IXOTH) ||
249 (s.st_mode & S_IXUSR) ||
250 (s.st_mode & S_IXGRP)))
251 return TRUE;
255 return FALSE;
256 #endif
259 #ifdef G_OS_WIN32
261 #undef g_file_test
263 /* Binary compatibility version. Not for newly compiled code. */
265 gboolean
266 g_file_test (const gchar *filename,
267 GFileTest test)
269 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
270 gboolean retval;
272 if (utf8_filename == NULL)
273 return FALSE;
275 retval = g_file_test_utf8 (utf8_filename, test);
277 g_free (utf8_filename);
279 return retval;
282 #endif
284 GQuark
285 g_file_error_quark (void)
287 static GQuark q = 0;
288 if (q == 0)
289 q = g_quark_from_static_string ("g-file-error-quark");
291 return q;
295 * g_file_error_from_errno:
296 * @err_no: an "errno" value
298 * Gets a #GFileError constant based on the passed-in @errno.
299 * For example, if you pass in %EEXIST this function returns
300 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
301 * assume that all #GFileError values will exist.
303 * Normally a #GFileError value goes into a #GError returned
304 * from a function that manipulates files. So you would use
305 * g_file_error_from_errno() when constructing a #GError.
307 * Return value: #GFileError corresponding to the given @errno
309 GFileError
310 g_file_error_from_errno (gint err_no)
312 switch (err_no)
314 #ifdef EEXIST
315 case EEXIST:
316 return G_FILE_ERROR_EXIST;
317 break;
318 #endif
320 #ifdef EISDIR
321 case EISDIR:
322 return G_FILE_ERROR_ISDIR;
323 break;
324 #endif
326 #ifdef EACCES
327 case EACCES:
328 return G_FILE_ERROR_ACCES;
329 break;
330 #endif
332 #ifdef ENAMETOOLONG
333 case ENAMETOOLONG:
334 return G_FILE_ERROR_NAMETOOLONG;
335 break;
336 #endif
338 #ifdef ENOENT
339 case ENOENT:
340 return G_FILE_ERROR_NOENT;
341 break;
342 #endif
344 #ifdef ENOTDIR
345 case ENOTDIR:
346 return G_FILE_ERROR_NOTDIR;
347 break;
348 #endif
350 #ifdef ENXIO
351 case ENXIO:
352 return G_FILE_ERROR_NXIO;
353 break;
354 #endif
356 #ifdef ENODEV
357 case ENODEV:
358 return G_FILE_ERROR_NODEV;
359 break;
360 #endif
362 #ifdef EROFS
363 case EROFS:
364 return G_FILE_ERROR_ROFS;
365 break;
366 #endif
368 #ifdef ETXTBSY
369 case ETXTBSY:
370 return G_FILE_ERROR_TXTBSY;
371 break;
372 #endif
374 #ifdef EFAULT
375 case EFAULT:
376 return G_FILE_ERROR_FAULT;
377 break;
378 #endif
380 #ifdef ELOOP
381 case ELOOP:
382 return G_FILE_ERROR_LOOP;
383 break;
384 #endif
386 #ifdef ENOSPC
387 case ENOSPC:
388 return G_FILE_ERROR_NOSPC;
389 break;
390 #endif
392 #ifdef ENOMEM
393 case ENOMEM:
394 return G_FILE_ERROR_NOMEM;
395 break;
396 #endif
398 #ifdef EMFILE
399 case EMFILE:
400 return G_FILE_ERROR_MFILE;
401 break;
402 #endif
404 #ifdef ENFILE
405 case ENFILE:
406 return G_FILE_ERROR_NFILE;
407 break;
408 #endif
410 #ifdef EBADF
411 case EBADF:
412 return G_FILE_ERROR_BADF;
413 break;
414 #endif
416 #ifdef EINVAL
417 case EINVAL:
418 return G_FILE_ERROR_INVAL;
419 break;
420 #endif
422 #ifdef EPIPE
423 case EPIPE:
424 return G_FILE_ERROR_PIPE;
425 break;
426 #endif
428 #ifdef EAGAIN
429 case EAGAIN:
430 return G_FILE_ERROR_AGAIN;
431 break;
432 #endif
434 #ifdef EINTR
435 case EINTR:
436 return G_FILE_ERROR_INTR;
437 break;
438 #endif
440 #ifdef EIO
441 case EIO:
442 return G_FILE_ERROR_IO;
443 break;
444 #endif
446 #ifdef EPERM
447 case EPERM:
448 return G_FILE_ERROR_PERM;
449 break;
450 #endif
452 #ifdef ENOSYS
453 case ENOSYS:
454 return G_FILE_ERROR_NOSYS;
455 break;
456 #endif
458 default:
459 return G_FILE_ERROR_FAILED;
460 break;
464 static gboolean
465 get_contents_stdio (const gchar *display_filename,
466 FILE *f,
467 gchar **contents,
468 gsize *length,
469 GError **error)
471 gchar buf[4096];
472 size_t bytes;
473 gchar *str = NULL;
474 size_t total_bytes = 0;
475 size_t total_allocated = 0;
477 g_assert (f != NULL);
479 while (!feof (f))
481 gint save_errno;
483 bytes = fread (buf, 1, sizeof (buf), f);
484 save_errno = errno;
486 while ((total_bytes + bytes + 1) > total_allocated)
488 if (str)
489 total_allocated *= 2;
490 else
491 total_allocated = MIN (bytes + 1, sizeof (buf));
493 str = g_try_realloc (str, total_allocated);
495 if (str == NULL)
497 g_set_error (error,
498 G_FILE_ERROR,
499 G_FILE_ERROR_NOMEM,
500 _("Could not allocate %lu bytes to read file \"%s\""),
501 (gulong) total_allocated,
502 display_filename);
504 goto error;
508 if (ferror (f))
510 g_set_error (error,
511 G_FILE_ERROR,
512 g_file_error_from_errno (save_errno),
513 _("Error reading file '%s': %s"),
514 display_filename,
515 g_strerror (save_errno));
517 goto error;
520 memcpy (str + total_bytes, buf, bytes);
521 total_bytes += bytes;
524 fclose (f);
526 str[total_bytes] = '\0';
528 if (length)
529 *length = total_bytes;
531 *contents = str;
533 return TRUE;
535 error:
537 g_free (str);
538 fclose (f);
540 return FALSE;
543 #ifndef G_OS_WIN32
545 static gboolean
546 get_contents_regfile (const gchar *display_filename,
547 struct stat *stat_buf,
548 gint fd,
549 gchar **contents,
550 gsize *length,
551 GError **error)
553 gchar *buf;
554 size_t bytes_read;
555 size_t size;
556 size_t alloc_size;
558 size = stat_buf->st_size;
560 alloc_size = size + 1;
561 buf = g_try_malloc (alloc_size);
563 if (buf == NULL)
565 g_set_error (error,
566 G_FILE_ERROR,
567 G_FILE_ERROR_NOMEM,
568 _("Could not allocate %lu bytes to read file \"%s\""),
569 (gulong) alloc_size,
570 display_filename);
572 goto error;
575 bytes_read = 0;
576 while (bytes_read < size)
578 gssize rc;
580 rc = read (fd, buf + bytes_read, size - bytes_read);
582 if (rc < 0)
584 if (errno != EINTR)
586 int save_errno = errno;
588 g_free (buf);
589 g_set_error (error,
590 G_FILE_ERROR,
591 g_file_error_from_errno (save_errno),
592 _("Failed to read from file '%s': %s"),
593 display_filename,
594 g_strerror (save_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 int save_errno = errno;
640 g_set_error (error,
641 G_FILE_ERROR,
642 g_file_error_from_errno (save_errno),
643 _("Failed to open file '%s': %s"),
644 display_filename,
645 g_strerror (save_errno));
646 g_free (display_filename);
648 return FALSE;
651 /* I don't think this will ever fail, aside from ENOMEM, but. */
652 if (fstat (fd, &stat_buf) < 0)
654 int save_errno = errno;
656 close (fd);
657 g_set_error (error,
658 G_FILE_ERROR,
659 g_file_error_from_errno (save_errno),
660 _("Failed to get attributes of file '%s': fstat() failed: %s"),
661 display_filename,
662 g_strerror (save_errno));
663 g_free (display_filename);
665 return FALSE;
668 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
670 gboolean retval = get_contents_regfile (display_filename,
671 &stat_buf,
673 contents,
674 length,
675 error);
676 g_free (display_filename);
678 return retval;
680 else
682 FILE *f;
683 gboolean retval;
685 f = fdopen (fd, "r");
687 if (f == NULL)
689 int save_errno = errno;
691 g_set_error (error,
692 G_FILE_ERROR,
693 g_file_error_from_errno (save_errno),
694 _("Failed to open file '%s': fdopen() failed: %s"),
695 display_filename,
696 g_strerror (save_errno));
697 g_free (display_filename);
699 return FALSE;
702 retval = get_contents_stdio (display_filename, f, contents, length, error);
703 g_free (display_filename);
705 return retval;
709 #else /* G_OS_WIN32 */
711 static gboolean
712 get_contents_win32 (const gchar *filename,
713 gchar **contents,
714 gsize *length,
715 GError **error)
717 FILE *f;
718 gboolean retval;
719 gchar *display_filename = g_filename_display_name (filename);
720 int save_errno;
722 f = g_fopen (filename, "rb");
723 save_errno = errno;
725 if (f == NULL)
727 g_set_error (error,
728 G_FILE_ERROR,
729 g_file_error_from_errno (save_errno),
730 _("Failed to open file '%s': %s"),
731 display_filename,
732 g_strerror (save_errno));
733 g_free (display_filename);
735 return FALSE;
738 retval = get_contents_stdio (display_filename, f, contents, length, error);
739 g_free (display_filename);
741 return retval;
744 #endif
747 * g_file_get_contents:
748 * @filename: name of a file to read contents from, in the GLib file name encoding
749 * @contents: location to store an allocated string
750 * @length: location to store length in bytes of the contents, or %NULL
751 * @error: return location for a #GError, or %NULL
753 * Reads an entire file into allocated memory, with good error
754 * checking.
756 * If the call was successful, it returns %TRUE and sets @contents to the file
757 * contents and @length to the length of the file contents in bytes. The string
758 * stored in @contents will be nul-terminated, so for text files you can pass
759 * %NULL for the @length argument. If the call was not successful, it returns
760 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
761 * codes are those in the #GFileError enumeration. In the error case,
762 * @contents is set to %NULL and @length is set to zero.
764 * Return value: %TRUE on success, %FALSE if an error occurred
766 gboolean
767 g_file_get_contents (const gchar *filename,
768 gchar **contents,
769 gsize *length,
770 GError **error)
772 g_return_val_if_fail (filename != NULL, FALSE);
773 g_return_val_if_fail (contents != NULL, FALSE);
775 *contents = NULL;
776 if (length)
777 *length = 0;
779 #ifdef G_OS_WIN32
780 return get_contents_win32 (filename, contents, length, error);
781 #else
782 return get_contents_posix (filename, contents, length, error);
783 #endif
786 #ifdef G_OS_WIN32
788 #undef g_file_get_contents
790 /* Binary compatibility version. Not for newly compiled code. */
792 gboolean
793 g_file_get_contents (const gchar *filename,
794 gchar **contents,
795 gsize *length,
796 GError **error)
798 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
799 gboolean retval;
801 if (utf8_filename == NULL)
802 return FALSE;
804 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
806 g_free (utf8_filename);
808 return retval;
811 #endif
814 static gboolean
815 rename_file (const char *old_name,
816 const char *new_name,
817 GError **err)
819 errno = 0;
820 if (g_rename (old_name, new_name) == -1)
822 int save_errno = errno;
823 gchar *display_old_name = g_filename_display_name (old_name);
824 gchar *display_new_name = g_filename_display_name (new_name);
826 g_set_error (err,
827 G_FILE_ERROR,
828 g_file_error_from_errno (save_errno),
829 _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
830 display_old_name,
831 display_new_name,
832 g_strerror (save_errno));
834 g_free (display_old_name);
835 g_free (display_new_name);
837 return FALSE;
840 return TRUE;
843 static gchar *
844 write_to_temp_file (const gchar *contents,
845 gssize length,
846 const gchar *template,
847 GError **err)
849 gchar *tmp_name;
850 gchar *display_name;
851 gchar *retval;
852 FILE *file;
853 gint fd;
854 int save_errno;
856 retval = NULL;
858 tmp_name = g_strdup_printf ("%s.XXXXXX", template);
860 errno = 0;
861 fd = g_mkstemp (tmp_name);
862 save_errno = errno;
863 display_name = g_filename_display_name (tmp_name);
865 if (fd == -1)
867 g_set_error (err,
868 G_FILE_ERROR,
869 g_file_error_from_errno (save_errno),
870 _("Failed to create file '%s': %s"),
871 display_name, g_strerror (save_errno));
873 goto out;
876 errno = 0;
877 file = fdopen (fd, "wb");
878 if (!file)
880 g_set_error (err,
881 G_FILE_ERROR,
882 g_file_error_from_errno (errno),
883 _("Failed to open file '%s' for writing: fdopen() failed: %s"),
884 display_name,
885 g_strerror (errno));
887 close (fd);
888 g_unlink (tmp_name);
890 goto out;
893 if (length > 0)
895 size_t n_written;
897 errno = 0;
899 n_written = fwrite (contents, 1, length, file);
901 if (n_written < length)
903 g_set_error (err,
904 G_FILE_ERROR,
905 g_file_error_from_errno (errno),
906 _("Failed to write file '%s': fwrite() failed: %s"),
907 display_name,
908 g_strerror (errno));
910 fclose (file);
911 g_unlink (tmp_name);
913 goto out;
917 errno = 0;
918 if (fclose (file) == EOF)
920 g_set_error (err,
921 G_FILE_ERROR,
922 g_file_error_from_errno (errno),
923 _("Failed to close file '%s': fclose() failed: %s"),
924 display_name,
925 g_strerror (errno));
927 g_unlink (tmp_name);
929 goto out;
932 retval = g_strdup (tmp_name);
934 out:
935 g_free (tmp_name);
936 g_free (display_name);
938 return retval;
942 * g_file_replace:
943 * @filename: name of a file to write @contents to, in the GLib file name
944 * encoding
945 * @contents: string to write to the file
946 * @length: length of @contents, or -1 if @contents is a nul-terminated string
947 * @error: return location for a #GError, or %NULL
949 * Writes all of @contents to a file named @filename, with good error checking.
950 * If a file called @filename already exists it will be overwritten.
952 * This write is atomic in the sense that it is first written to a temporary
953 * file which is then renamed to the final name. Notes:
954 * <itemizedlist>
955 * <listitem>
956 * On Unix, if @filename already exists hard links to @filename will break.
957 * Also since the file is recreated, existing permissions, access control
958 * lists, metadata etc. may be lost. If @filename is a symbolic link,
959 * the link itself will be replaced, not the linked file.
960 * </listitem>
961 * <listitem>
962 * On Windows renaming a file will not remove an existing file with the
963 * new name, so on Windows there is a race condition between the existing
964 * file being removed and the temporary file being renamed.
965 * </listitem>
966 * <listitem>
967 * On Windows there is no way to remove a file that is open to some
968 * process, or mapped into memory. Thus, this function will fail if
969 * @filename already exists and is open.
970 * </listitem>
971 * </itemizedlist>
973 * If the call was sucessful, it returns %TRUE. If the call was not successful,
974 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
975 * Possible error codes are those in the #GFileError enumeration.
977 * Return value: %TRUE on success, %FALSE if an error occurred
979 * Since: 2.8
981 gboolean
982 g_file_replace (const gchar *filename,
983 const gchar *contents,
984 gssize length,
985 GError **error)
987 gchar *tmp_filename;
988 gboolean retval;
989 GError *rename_error = NULL;
991 g_return_val_if_fail (filename != NULL, FALSE);
992 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
993 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
994 g_return_val_if_fail (length >= -1, FALSE);
996 if (length == -1)
997 length = strlen (contents);
999 tmp_filename = write_to_temp_file (contents, length, filename, error);
1001 if (!tmp_filename)
1003 retval = FALSE;
1004 goto out;
1007 if (!rename_file (tmp_filename, filename, &rename_error))
1009 #ifndef G_OS_WIN32
1011 g_unlink (tmp_filename);
1012 g_propagate_error (error, rename_error);
1013 retval = FALSE;
1014 goto out;
1016 #else /* G_OS_WIN32 */
1018 /* Renaming failed, but on Windows this may just mean
1019 * the file already exists. So if the target file
1020 * exists, try deleting it and do the rename again.
1022 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1024 g_unlink (tmp_filename);
1025 g_propagate_error (error, rename_error);
1026 retval = FALSE;
1027 goto out;
1030 g_error_free (rename_error);
1032 if (g_unlink (filename) == -1)
1034 gchar *display_filename = g_filename_display_name (filename);
1036 g_set_error (error,
1037 G_FILE_ERROR,
1038 g_file_error_from_errno (errno),
1039 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1040 display_filename,
1041 g_strerror (errno));
1043 g_free (display_filename);
1044 g_unlink (tmp_filename);
1045 retval = FALSE;
1046 goto out;
1049 if (!rename_file (tmp_filename, filename, error))
1051 g_unlink (tmp_filename);
1052 retval = FALSE;
1053 goto out;
1056 #endif
1059 retval = TRUE;
1061 out:
1062 g_free (tmp_filename);
1063 return retval;
1067 * mkstemp() implementation is from the GNU C library.
1068 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1071 * g_mkstemp:
1072 * @tmpl: template filename
1074 * Opens a temporary file. See the mkstemp() documentation
1075 * on most UNIX-like systems. This is a portability wrapper, which simply calls
1076 * mkstemp() on systems that have it, and implements
1077 * it in GLib otherwise.
1079 * The parameter is a string that should match the rules for
1080 * mkstemp(), i.e. end in "XXXXXX". The X string will
1081 * be modified to form the name of a file that didn't exist.
1082 * The string should be in the GLib file name encoding. Most importantly,
1083 * on Windows it should be in UTF-8.
1085 * Return value: A file handle (as from open()) to the file
1086 * opened for reading and writing. The file is opened in binary mode
1087 * on platforms where there is a difference. The file handle should be
1088 * closed with close(). In case of errors, -1 is returned.
1090 gint
1091 g_mkstemp (gchar *tmpl)
1093 #ifdef HAVE_MKSTEMP
1094 return mkstemp (tmpl);
1095 #else
1096 int len;
1097 char *XXXXXX;
1098 int count, fd;
1099 static const char letters[] =
1100 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1101 static const int NLETTERS = sizeof (letters) - 1;
1102 glong value;
1103 GTimeVal tv;
1104 static int counter = 0;
1106 len = strlen (tmpl);
1107 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
1109 errno = EINVAL;
1110 return -1;
1113 /* This is where the Xs start. */
1114 XXXXXX = &tmpl[len - 6];
1116 /* Get some more or less random data. */
1117 g_get_current_time (&tv);
1118 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1120 for (count = 0; count < 100; value += 7777, ++count)
1122 glong v = value;
1124 /* Fill in the random bits. */
1125 XXXXXX[0] = letters[v % NLETTERS];
1126 v /= NLETTERS;
1127 XXXXXX[1] = letters[v % NLETTERS];
1128 v /= NLETTERS;
1129 XXXXXX[2] = letters[v % NLETTERS];
1130 v /= NLETTERS;
1131 XXXXXX[3] = letters[v % NLETTERS];
1132 v /= NLETTERS;
1133 XXXXXX[4] = letters[v % NLETTERS];
1134 v /= NLETTERS;
1135 XXXXXX[5] = letters[v % NLETTERS];
1137 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1138 fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1140 if (fd >= 0)
1141 return fd;
1142 else if (errno != EEXIST)
1143 /* Any other error will apply also to other names we might
1144 * try, and there are 2^32 or so of them, so give up now.
1146 return -1;
1149 /* We got out of the loop because we ran out of combinations to try. */
1150 errno = EEXIST;
1151 return -1;
1152 #endif
1155 #ifdef G_OS_WIN32
1157 #undef g_mkstemp
1159 /* Binary compatibility version. Not for newly compiled code. */
1161 gint
1162 g_mkstemp (gchar *tmpl)
1164 int len;
1165 char *XXXXXX;
1166 int count, fd;
1167 static const char letters[] =
1168 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1169 static const int NLETTERS = sizeof (letters) - 1;
1170 glong value;
1171 GTimeVal tv;
1172 static int counter = 0;
1174 len = strlen (tmpl);
1175 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
1177 errno = EINVAL;
1178 return -1;
1181 /* This is where the Xs start. */
1182 XXXXXX = &tmpl[len - 6];
1184 /* Get some more or less random data. */
1185 g_get_current_time (&tv);
1186 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1188 for (count = 0; count < 100; value += 7777, ++count)
1190 glong v = value;
1192 /* Fill in the random bits. */
1193 XXXXXX[0] = letters[v % NLETTERS];
1194 v /= NLETTERS;
1195 XXXXXX[1] = letters[v % NLETTERS];
1196 v /= NLETTERS;
1197 XXXXXX[2] = letters[v % NLETTERS];
1198 v /= NLETTERS;
1199 XXXXXX[3] = letters[v % NLETTERS];
1200 v /= NLETTERS;
1201 XXXXXX[4] = letters[v % NLETTERS];
1202 v /= NLETTERS;
1203 XXXXXX[5] = letters[v % NLETTERS];
1205 /* This is the backward compatibility system codepage version,
1206 * thus use normal open().
1208 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1210 if (fd >= 0)
1211 return fd;
1212 else if (errno != EEXIST)
1213 /* Any other error will apply also to other names we might
1214 * try, and there are 2^32 or so of them, so give up now.
1216 return -1;
1219 /* We got out of the loop because we ran out of combinations to try. */
1220 errno = EEXIST;
1221 return -1;
1224 #endif
1227 * g_file_open_tmp:
1228 * @tmpl: Template for file name, as in g_mkstemp(), basename only
1229 * @name_used: location to store actual name used
1230 * @error: return location for a #GError
1232 * Opens a file for writing in the preferred directory for temporary
1233 * files (as returned by g_get_tmp_dir()).
1235 * @tmpl should be a string in the GLib file name encoding ending with
1236 * six 'X' characters, as the parameter to g_mkstemp() (or mkstemp()).
1237 * However, unlike these functions, the template should only be a
1238 * basename, no directory components are allowed. If template is
1239 * %NULL, a default template is used.
1241 * Note that in contrast to g_mkstemp() (and mkstemp())
1242 * @tmpl is not modified, and might thus be a read-only literal string.
1244 * The actual name used is returned in @name_used if non-%NULL. This
1245 * string should be freed with g_free() when not needed any longer.
1246 * The returned name is in the GLib file name encoding.
1248 * Return value: A file handle (as from open()) to
1249 * the file opened for reading and writing. The file is opened in binary
1250 * mode on platforms where there is a difference. The file handle should be
1251 * closed with close(). In case of errors, -1 is returned
1252 * and @error will be set.
1254 gint
1255 g_file_open_tmp (const gchar *tmpl,
1256 gchar **name_used,
1257 GError **error)
1259 int retval;
1260 const char *tmpdir;
1261 char *sep;
1262 char *fulltemplate;
1263 const char *slash;
1265 if (tmpl == NULL)
1266 tmpl = ".XXXXXX";
1268 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1269 #ifdef G_OS_WIN32
1270 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1271 #endif
1274 gchar *display_tmpl = g_filename_display_name (tmpl);
1275 char c[2];
1276 c[0] = *slash;
1277 c[1] = '\0';
1279 g_set_error (error,
1280 G_FILE_ERROR,
1281 G_FILE_ERROR_FAILED,
1282 _("Template '%s' invalid, should not contain a '%s'"),
1283 display_tmpl, c);
1284 g_free (display_tmpl);
1286 return -1;
1289 if (strlen (tmpl) < 6 ||
1290 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
1292 gchar *display_tmpl = g_filename_display_name (tmpl);
1293 g_set_error (error,
1294 G_FILE_ERROR,
1295 G_FILE_ERROR_FAILED,
1296 _("Template '%s' doesn't end with XXXXXX"),
1297 display_tmpl);
1298 g_free (display_tmpl);
1299 return -1;
1302 tmpdir = g_get_tmp_dir ();
1304 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1305 sep = "";
1306 else
1307 sep = G_DIR_SEPARATOR_S;
1309 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1311 retval = g_mkstemp (fulltemplate);
1313 if (retval == -1)
1315 int save_errno = errno;
1316 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1318 g_set_error (error,
1319 G_FILE_ERROR,
1320 g_file_error_from_errno (save_errno),
1321 _("Failed to create file '%s': %s"),
1322 display_fulltemplate, g_strerror (save_errno));
1323 g_free (display_fulltemplate);
1324 g_free (fulltemplate);
1325 return -1;
1328 if (name_used)
1329 *name_used = fulltemplate;
1330 else
1331 g_free (fulltemplate);
1333 return retval;
1336 #ifdef G_OS_WIN32
1338 #undef g_file_open_tmp
1340 /* Binary compatibility version. Not for newly compiled code. */
1342 gint
1343 g_file_open_tmp (const gchar *tmpl,
1344 gchar **name_used,
1345 GError **error)
1347 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1348 gchar *utf8_name_used;
1349 gint retval;
1351 if (utf8_tmpl == NULL)
1352 return -1;
1354 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1356 if (retval == -1)
1357 return -1;
1359 if (name_used)
1360 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1362 g_free (utf8_name_used);
1364 return retval;
1367 #endif
1369 static gchar *
1370 g_build_pathv (const gchar *separator,
1371 const gchar *first_element,
1372 va_list args)
1374 GString *result;
1375 gint separator_len = strlen (separator);
1376 gboolean is_first = TRUE;
1377 gboolean have_leading = FALSE;
1378 const gchar *single_element = NULL;
1379 const gchar *next_element;
1380 const gchar *last_trailing = NULL;
1382 result = g_string_new (NULL);
1384 next_element = first_element;
1386 while (TRUE)
1388 const gchar *element;
1389 const gchar *start;
1390 const gchar *end;
1392 if (next_element)
1394 element = next_element;
1395 next_element = va_arg (args, gchar *);
1397 else
1398 break;
1400 /* Ignore empty elements */
1401 if (!*element)
1402 continue;
1404 start = element;
1406 if (separator_len)
1408 while (start &&
1409 strncmp (start, separator, separator_len) == 0)
1410 start += separator_len;
1413 end = start + strlen (start);
1415 if (separator_len)
1417 while (end >= start + separator_len &&
1418 strncmp (end - separator_len, separator, separator_len) == 0)
1419 end -= separator_len;
1421 last_trailing = end;
1422 while (last_trailing >= element + separator_len &&
1423 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1424 last_trailing -= separator_len;
1426 if (!have_leading)
1428 /* If the leading and trailing separator strings are in the
1429 * same element and overlap, the result is exactly that element
1431 if (last_trailing <= start)
1432 single_element = element;
1434 g_string_append_len (result, element, start - element);
1435 have_leading = TRUE;
1437 else
1438 single_element = NULL;
1441 if (end == start)
1442 continue;
1444 if (!is_first)
1445 g_string_append (result, separator);
1447 g_string_append_len (result, start, end - start);
1448 is_first = FALSE;
1451 if (single_element)
1453 g_string_free (result, TRUE);
1454 return g_strdup (single_element);
1456 else
1458 if (last_trailing)
1459 g_string_append (result, last_trailing);
1461 return g_string_free (result, FALSE);
1466 * g_build_path:
1467 * @separator: a string used to separator the elements of the path.
1468 * @first_element: the first element in the path
1469 * @Varargs: remaining elements in path, terminated by %NULL
1471 * Creates a path from a series of elements using @separator as the
1472 * separator between elements. At the boundary between two elements,
1473 * any trailing occurrences of separator in the first element, or
1474 * leading occurrences of separator in the second element are removed
1475 * and exactly one copy of the separator is inserted.
1477 * Empty elements are ignored.
1479 * The number of leading copies of the separator on the result is
1480 * the same as the number of leading copies of the separator on
1481 * the first non-empty element.
1483 * The number of trailing copies of the separator on the result is
1484 * the same as the number of trailing copies of the separator on
1485 * the last non-empty element. (Determination of the number of
1486 * trailing copies is done without stripping leading copies, so
1487 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1488 * has 1 trailing copy.)
1490 * However, if there is only a single non-empty element, and there
1491 * are no characters in that element not part of the leading or
1492 * trailing separators, then the result is exactly the original value
1493 * of that element.
1495 * Other than for determination of the number of leading and trailing
1496 * copies of the separator, elements consisting only of copies
1497 * of the separator are ignored.
1499 * Return value: a newly-allocated string that must be freed with g_free().
1501 gchar *
1502 g_build_path (const gchar *separator,
1503 const gchar *first_element,
1504 ...)
1506 gchar *str;
1507 va_list args;
1509 g_return_val_if_fail (separator != NULL, NULL);
1511 va_start (args, first_element);
1512 str = g_build_pathv (separator, first_element, args);
1513 va_end (args);
1515 return str;
1519 * g_build_filename:
1520 * @first_element: the first element in the path
1521 * @Varargs: remaining elements in path, terminated by %NULL
1523 * Creates a filename from a series of elements using the correct
1524 * separator for filenames.
1526 * On Unix, this function behaves identically to <literal>g_build_path
1527 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1529 * On Windows, it takes into account that either the backslash
1530 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1531 * as separator in filenames, but otherwise behaves as on Unix. When
1532 * file pathname separators need to be inserted, the one that last
1533 * previously occurred in the parameters (reading from left to right)
1534 * is used.
1536 * No attempt is made to force the resulting filename to be an absolute
1537 * path. If the first element is a relative path, the result will
1538 * be a relative path.
1540 * Return value: a newly-allocated string that must be freed with g_free().
1542 gchar *
1543 g_build_filename (const gchar *first_element,
1544 ...)
1546 #ifndef G_OS_WIN32
1547 gchar *str;
1548 va_list args;
1550 va_start (args, first_element);
1551 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
1552 va_end (args);
1554 return str;
1555 #else
1556 /* Code copied from g_build_pathv(), and modifed to use two
1557 * alternative single-character separators.
1559 va_list args;
1560 GString *result;
1561 gboolean is_first = TRUE;
1562 gboolean have_leading = FALSE;
1563 const gchar *single_element = NULL;
1564 const gchar *next_element;
1565 const gchar *last_trailing = NULL;
1566 gchar current_separator = '\\';
1568 va_start (args, first_element);
1570 result = g_string_new (NULL);
1572 next_element = first_element;
1574 while (TRUE)
1576 const gchar *element;
1577 const gchar *start;
1578 const gchar *end;
1580 if (next_element)
1582 element = next_element;
1583 next_element = va_arg (args, gchar *);
1585 else
1586 break;
1588 /* Ignore empty elements */
1589 if (!*element)
1590 continue;
1592 start = element;
1594 if (TRUE)
1596 while (start &&
1597 (*start == '\\' || *start == '/'))
1599 current_separator = *start;
1600 start++;
1604 end = start + strlen (start);
1606 if (TRUE)
1608 while (end >= start + 1 &&
1609 (end[-1] == '\\' || end[-1] == '/'))
1611 current_separator = end[-1];
1612 end--;
1615 last_trailing = end;
1616 while (last_trailing >= element + 1 &&
1617 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1618 last_trailing--;
1620 if (!have_leading)
1622 /* If the leading and trailing separator strings are in the
1623 * same element and overlap, the result is exactly that element
1625 if (last_trailing <= start)
1626 single_element = element;
1628 g_string_append_len (result, element, start - element);
1629 have_leading = TRUE;
1631 else
1632 single_element = NULL;
1635 if (end == start)
1636 continue;
1638 if (!is_first)
1639 g_string_append_len (result, &current_separator, 1);
1641 g_string_append_len (result, start, end - start);
1642 is_first = FALSE;
1645 va_end (args);
1647 if (single_element)
1649 g_string_free (result, TRUE);
1650 return g_strdup (single_element);
1652 else
1654 if (last_trailing)
1655 g_string_append (result, last_trailing);
1657 return g_string_free (result, FALSE);
1659 #endif
1663 * g_file_read_link:
1664 * @filename: the symbolic link
1665 * @error: return location for a #GError
1667 * Reads the contents of the symbolic link @filename like the POSIX
1668 * readlink() function. The returned string is in the encoding used
1669 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1671 * Returns: A newly allocated string with the contents of the symbolic link,
1672 * or %NULL if an error occurred.
1674 * Since: 2.4
1676 gchar *
1677 g_file_read_link (const gchar *filename,
1678 GError **error)
1680 #ifdef HAVE_READLINK
1681 gchar *buffer;
1682 guint size;
1683 gint read_size;
1685 size = 256;
1686 buffer = g_malloc (size);
1688 while (TRUE)
1690 read_size = readlink (filename, buffer, size);
1691 if (read_size < 0) {
1692 int save_errno = errno;
1693 gchar *display_filename = g_filename_display_name (filename);
1695 g_free (buffer);
1696 g_set_error (error,
1697 G_FILE_ERROR,
1698 g_file_error_from_errno (save_errno),
1699 _("Failed to read the symbolic link '%s': %s"),
1700 display_filename,
1701 g_strerror (save_errno));
1702 g_free (display_filename);
1704 return NULL;
1707 if (read_size < size)
1709 buffer[read_size] = 0;
1710 return buffer;
1713 size *= 2;
1714 buffer = g_realloc (buffer, size);
1716 #else
1717 g_set_error (error,
1718 G_FILE_ERROR,
1719 G_FILE_ERROR_INVAL,
1720 _("Symbolic links not supported"));
1722 return NULL;
1723 #endif
1726 #define __G_FILEUTILS_C__
1727 #include "galiasdef.c"