1 /* gfileutils.c - File utility functions
3 * Copyright 2000 Red Hat, Inc.
5 * GLib is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU Lesser General Public License as
7 * published by the Free Software Foundation; either version 2 of the
8 * License, or (at your option) any later version.
10 * GLib is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with GLib; see the file COPYING.LIB. If not,
17 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 * Boston, MA 02111-1307, USA.
34 #include <sys/types.h>
43 #endif /* G_OS_WIN32 */
60 * @filename: a filename to test in the GLib file name encoding
61 * @test: bitfield of #GFileTest flags
63 * Returns %TRUE if any of the tests in the bitfield @test are
64 * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS |
65 * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists;
66 * the check whether it's a directory doesn't matter since the existence
67 * test is %TRUE. With the current set of available tests, there's no point
68 * passing in more than one test at a time.
70 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
71 * so for a symbolic link to a regular file g_file_test() will return
72 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
74 * Note, that for a dangling symbolic link g_file_test() will return
75 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
77 * You should never use g_file_test() to test whether it is safe
78 * to perform an operation, because there is always the possibility
79 * of the condition changing before you actually perform the operation.
80 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
81 * to know whether it is is safe to write to a file without being
82 * tricked into writing into a different location. It doesn't work!
84 * <informalexample><programlisting>
85 * /* DON'T DO THIS */
86 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) {
87 * fd = g_open (filename, O_WRONLY);
88 * /* write to fd */
90 * </programlisting></informalexample>
92 * Another thing to note is that %G_FILE_TEST_EXISTS and
93 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
94 * system call. This usually doesn't matter, but if your program
95 * is setuid or setgid it means that these tests will give you
96 * the answer for the real user ID and group ID, rather than the
97 * effective user ID and group ID.
99 * On Windows, there are no symlinks, so testing for
100 * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
101 * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
102 * its name indicates that it is executable, checking for well-known
103 * extensions and those listed in the %PATHEXT environment variable.
105 * Return value: whether a test was %TRUE
108 g_file_test (const gchar *filename,
112 /* stuff missing in std vc6 api */
113 # ifndef INVALID_FILE_ATTRIBUTES
114 # define INVALID_FILE_ATTRIBUTES -1
116 # ifndef FILE_ATTRIBUTE_DEVICE
117 # define FILE_ATTRIBUTE_DEVICE 64
121 if (G_WIN32_HAVE_WIDECHAR_API ())
123 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
125 if (wfilename == NULL)
128 attributes = GetFileAttributesW (wfilename);
134 gchar *cpfilename = g_locale_from_utf8 (filename, -1, NULL, NULL, NULL);
136 if (cpfilename == NULL)
139 attributes = GetFileAttributesA (cpfilename);
144 if (attributes == INVALID_FILE_ATTRIBUTES)
147 if (test & G_FILE_TEST_EXISTS)
150 if (test & G_FILE_TEST_IS_REGULAR)
151 return (attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0;
153 if (test & G_FILE_TEST_IS_DIR)
154 return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
156 if (test & G_FILE_TEST_IS_EXECUTABLE)
158 const gchar *lastdot = strrchr (filename, '.');
159 const gchar *pathext = NULL, *p;
165 if (stricmp (lastdot, ".exe") == 0 ||
166 stricmp (lastdot, ".cmd") == 0 ||
167 stricmp (lastdot, ".bat") == 0 ||
168 stricmp (lastdot, ".com") == 0)
171 /* Check if it is one of the types listed in %PATHEXT% */
173 pathext = g_getenv ("PATHEXT");
177 pathext = g_utf8_casefold (pathext, -1);
179 lastdot = g_utf8_casefold (lastdot, -1);
180 extlen = strlen (lastdot);
185 const gchar *q = strchr (p, ';');
188 if (extlen == q - p &&
189 memcmp (lastdot, p, extlen) == 0)
191 g_free ((gchar *) pathext);
192 g_free ((gchar *) lastdot);
201 g_free ((gchar *) pathext);
202 g_free ((gchar *) lastdot);
208 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
211 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
216 /* For root, on some POSIX systems, access (filename, X_OK)
217 * will succeed even if no executable bits are set on the
218 * file. We fall through to a stat test to avoid that.
222 test &= ~G_FILE_TEST_IS_EXECUTABLE;
224 if (test & G_FILE_TEST_IS_SYMLINK)
228 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
232 if (test & (G_FILE_TEST_IS_REGULAR |
234 G_FILE_TEST_IS_EXECUTABLE))
238 if (stat (filename, &s) == 0)
240 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
243 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
246 /* The extra test for root when access (file, X_OK) succeeds.
248 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
249 ((s.st_mode & S_IXOTH) ||
250 (s.st_mode & S_IXUSR) ||
251 (s.st_mode & S_IXGRP)))
264 /* Binary compatibility version. Not for newly compiled code. */
267 g_file_test (const gchar *filename,
270 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
273 if (utf8_filename == NULL)
276 retval = g_file_test_utf8 (utf8_filename, test);
278 g_free (utf8_filename);
286 g_file_error_quark (void)
290 q = g_quark_from_static_string ("g-file-error-quark");
296 * g_file_error_from_errno:
297 * @err_no: an "errno" value
299 * Gets a #GFileError constant based on the passed-in @errno.
300 * For example, if you pass in %EEXIST this function returns
301 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
302 * assume that all #GFileError values will exist.
304 * Normally a #GFileError value goes into a #GError returned
305 * from a function that manipulates files. So you would use
306 * g_file_error_from_errno() when constructing a #GError.
308 * Return value: #GFileError corresponding to the given @errno
311 g_file_error_from_errno (gint err_no)
317 return G_FILE_ERROR_EXIST;
323 return G_FILE_ERROR_ISDIR;
329 return G_FILE_ERROR_ACCES;
335 return G_FILE_ERROR_NAMETOOLONG;
341 return G_FILE_ERROR_NOENT;
347 return G_FILE_ERROR_NOTDIR;
353 return G_FILE_ERROR_NXIO;
359 return G_FILE_ERROR_NODEV;
365 return G_FILE_ERROR_ROFS;
371 return G_FILE_ERROR_TXTBSY;
377 return G_FILE_ERROR_FAULT;
383 return G_FILE_ERROR_LOOP;
389 return G_FILE_ERROR_NOSPC;
395 return G_FILE_ERROR_NOMEM;
401 return G_FILE_ERROR_MFILE;
407 return G_FILE_ERROR_NFILE;
413 return G_FILE_ERROR_BADF;
419 return G_FILE_ERROR_INVAL;
425 return G_FILE_ERROR_PIPE;
431 return G_FILE_ERROR_AGAIN;
437 return G_FILE_ERROR_INTR;
443 return G_FILE_ERROR_IO;
449 return G_FILE_ERROR_PERM;
455 return G_FILE_ERROR_NOSYS;
460 return G_FILE_ERROR_FAILED;
466 get_contents_stdio (const gchar *display_filename,
475 size_t total_bytes = 0;
476 size_t total_allocated = 0;
479 g_assert (f != NULL);
485 bytes = fread (buf, 1, sizeof (buf), f);
488 while ((total_bytes + bytes + 1) > total_allocated)
491 total_allocated *= 2;
493 total_allocated = MIN (bytes + 1, sizeof (buf));
495 tmp = g_try_realloc (str, total_allocated);
502 _("Could not allocate %lu bytes to read file \"%s\""),
503 (gulong) total_allocated,
516 g_file_error_from_errno (save_errno),
517 _("Error reading file '%s': %s"),
519 g_strerror (save_errno));
524 memcpy (str + total_bytes, buf, bytes);
525 total_bytes += bytes;
530 if (total_allocated == 0)
531 str = g_new (gchar, 1);
533 str[total_bytes] = '\0';
536 *length = total_bytes;
553 get_contents_regfile (const gchar *display_filename,
554 struct stat *stat_buf,
565 size = stat_buf->st_size;
567 alloc_size = size + 1;
568 buf = g_try_malloc (alloc_size);
575 _("Could not allocate %lu bytes to read file \"%s\""),
583 while (bytes_read < size)
587 rc = read (fd, buf + bytes_read, size - bytes_read);
593 int save_errno = errno;
598 g_file_error_from_errno (save_errno),
599 _("Failed to read from file '%s': %s"),
601 g_strerror (save_errno));
612 buf[bytes_read] = '\0';
615 *length = bytes_read;
631 get_contents_posix (const gchar *filename,
636 struct stat stat_buf;
638 gchar *display_filename = g_filename_display_name (filename);
640 /* O_BINARY useful on Cygwin */
641 fd = open (filename, O_RDONLY|O_BINARY);
645 int save_errno = errno;
649 g_file_error_from_errno (save_errno),
650 _("Failed to open file '%s': %s"),
652 g_strerror (save_errno));
653 g_free (display_filename);
658 /* I don't think this will ever fail, aside from ENOMEM, but. */
659 if (fstat (fd, &stat_buf) < 0)
661 int save_errno = errno;
666 g_file_error_from_errno (save_errno),
667 _("Failed to get attributes of file '%s': fstat() failed: %s"),
669 g_strerror (save_errno));
670 g_free (display_filename);
675 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
677 gboolean retval = get_contents_regfile (display_filename,
683 g_free (display_filename);
692 f = fdopen (fd, "r");
696 int save_errno = errno;
700 g_file_error_from_errno (save_errno),
701 _("Failed to open file '%s': fdopen() failed: %s"),
703 g_strerror (save_errno));
704 g_free (display_filename);
709 retval = get_contents_stdio (display_filename, f, contents, length, error);
710 g_free (display_filename);
716 #else /* G_OS_WIN32 */
719 get_contents_win32 (const gchar *filename,
726 gchar *display_filename = g_filename_display_name (filename);
729 f = g_fopen (filename, "rb");
736 g_file_error_from_errno (save_errno),
737 _("Failed to open file '%s': %s"),
739 g_strerror (save_errno));
740 g_free (display_filename);
745 retval = get_contents_stdio (display_filename, f, contents, length, error);
746 g_free (display_filename);
754 * g_file_get_contents:
755 * @filename: name of a file to read contents from, in the GLib file name encoding
756 * @contents: location to store an allocated string
757 * @length: location to store length in bytes of the contents, or %NULL
758 * @error: return location for a #GError, or %NULL
760 * Reads an entire file into allocated memory, with good error
763 * If the call was successful, it returns %TRUE and sets @contents to the file
764 * contents and @length to the length of the file contents in bytes. The string
765 * stored in @contents will be nul-terminated, so for text files you can pass
766 * %NULL for the @length argument. If the call was not successful, it returns
767 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
768 * codes are those in the #GFileError enumeration. In the error case,
769 * @contents is set to %NULL and @length is set to zero.
771 * Return value: %TRUE on success, %FALSE if an error occurred
774 g_file_get_contents (const gchar *filename,
779 g_return_val_if_fail (filename != NULL, FALSE);
780 g_return_val_if_fail (contents != NULL, FALSE);
787 return get_contents_win32 (filename, contents, length, error);
789 return get_contents_posix (filename, contents, length, error);
795 #undef g_file_get_contents
797 /* Binary compatibility version. Not for newly compiled code. */
800 g_file_get_contents (const gchar *filename,
805 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
808 if (utf8_filename == NULL)
811 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
813 g_free (utf8_filename);
821 rename_file (const char *old_name,
822 const char *new_name,
826 if (g_rename (old_name, new_name) == -1)
828 int save_errno = errno;
829 gchar *display_old_name = g_filename_display_name (old_name);
830 gchar *display_new_name = g_filename_display_name (new_name);
834 g_file_error_from_errno (save_errno),
835 _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
838 g_strerror (save_errno));
840 g_free (display_old_name);
841 g_free (display_new_name);
850 set_umask_permissions (int fd,
858 /* All of this function is just to work around the fact that
859 * there is no way to get the umask without changing it.
861 * We can't just change-and-reset the umask because that would
862 * lead to a race condition if another thread tried to change
863 * the umask in between the getting and the setting of the umask.
864 * So we have to do the whole thing in a child process.
877 g_file_error_from_errno (save_errno),
878 _("Could not change file mode: fork() failed: %s"),
879 g_strerror (save_errno));
886 mode_t mask = umask (0666);
889 if (fchmod (fd, 0666 & ~mask) == -1)
894 return TRUE; /* To quiet gcc */
902 if (waitpid (pid, &status, 0) == -1)
908 g_file_error_from_errno (save_errno),
909 _("Could not change file mode: waitpid() failed: %s"),
910 g_strerror (save_errno));
915 if (WIFEXITED (status))
917 save_errno = WEXITSTATUS (status);
927 g_file_error_from_errno (save_errno),
928 _("Could not change file mode: chmod() failed: %s"),
929 g_strerror (save_errno));
934 else if (WIFSIGNALED (status))
939 _("Could not change file mode: Child terminated by signal: %s"),
940 g_strsignal (WTERMSIG (status)));
946 /* This shouldn't happen */
950 _("Could not change file mode: Child terminated abnormally"));
958 write_to_temp_file (const gchar *contents,
960 const gchar *template,
972 tmp_name = g_strdup_printf ("%s.XXXXXX", template);
975 fd = g_mkstemp (tmp_name);
976 display_name = g_filename_display_name (tmp_name);
983 g_file_error_from_errno (save_errno),
984 _("Failed to create file '%s': %s"),
985 display_name, g_strerror (save_errno));
990 if (!set_umask_permissions (fd, err))
999 file = fdopen (fd, "wb");
1005 g_file_error_from_errno (save_errno),
1006 _("Failed to open file '%s' for writing: fdopen() failed: %s"),
1008 g_strerror (save_errno));
1011 g_unlink (tmp_name);
1022 n_written = fwrite (contents, 1, length, file);
1024 if (n_written < length)
1030 g_file_error_from_errno (save_errno),
1031 _("Failed to write file '%s': fwrite() failed: %s"),
1033 g_strerror (save_errno));
1036 g_unlink (tmp_name);
1043 if (fclose (file) == EOF)
1049 g_file_error_from_errno (save_errno),
1050 _("Failed to close file '%s': fclose() failed: %s"),
1052 g_strerror (save_errno));
1054 g_unlink (tmp_name);
1059 retval = g_strdup (tmp_name);
1063 g_free (display_name);
1070 * @filename: name of a file to write @contents to, in the GLib file name
1072 * @contents: string to write to the file
1073 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1074 * @error: return location for a #GError, or %NULL
1076 * Writes all of @contents to a file named @filename, with good error checking.
1077 * If a file called @filename already exists it will be overwritten.
1079 * This write is atomic in the sense that it is first written to a temporary
1080 * file which is then renamed to the final name. Notes:
1083 * On Unix, if @filename already exists hard links to @filename will break.
1084 * Also since the file is recreated, existing permissions, access control
1085 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1086 * the link itself will be replaced, not the linked file.
1089 * On Windows renaming a file will not remove an existing file with the
1090 * new name, so on Windows there is a race condition between the existing
1091 * file being removed and the temporary file being renamed.
1094 * On Windows there is no way to remove a file that is open to some
1095 * process, or mapped into memory. Thus, this function will fail if
1096 * @filename already exists and is open.
1100 * If the call was sucessful, it returns %TRUE. If the call was not successful,
1101 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1102 * Possible error codes are those in the #GFileError enumeration.
1104 * Return value: %TRUE on success, %FALSE if an error occurred
1109 g_file_replace (const gchar *filename,
1110 const gchar *contents,
1114 gchar *tmp_filename;
1116 GError *rename_error = NULL;
1118 g_return_val_if_fail (filename != NULL, FALSE);
1119 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1120 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1121 g_return_val_if_fail (length >= -1, FALSE);
1124 length = strlen (contents);
1126 tmp_filename = write_to_temp_file (contents, length, filename, error);
1134 if (!rename_file (tmp_filename, filename, &rename_error))
1138 g_unlink (tmp_filename);
1139 g_propagate_error (error, rename_error);
1143 #else /* G_OS_WIN32 */
1145 /* Renaming failed, but on Windows this may just mean
1146 * the file already exists. So if the target file
1147 * exists, try deleting it and do the rename again.
1149 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1151 g_unlink (tmp_filename);
1152 g_propagate_error (error, rename_error);
1157 g_error_free (rename_error);
1159 if (g_unlink (filename) == -1)
1161 gchar *display_filename = g_filename_display_name (filename);
1167 g_file_error_from_errno (save_errno),
1168 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1170 g_strerror (save_errno));
1172 g_free (display_filename);
1173 g_unlink (tmp_filename);
1178 if (!rename_file (tmp_filename, filename, error))
1180 g_unlink (tmp_filename);
1191 g_free (tmp_filename);
1196 * mkstemp() implementation is from the GNU C library.
1197 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1201 * @tmpl: template filename
1203 * Opens a temporary file. See the mkstemp() documentation
1204 * on most UNIX-like systems. This is a portability wrapper, which simply calls
1205 * mkstemp() on systems that have it, and implements
1206 * it in GLib otherwise.
1208 * The parameter is a string that should match the rules for
1209 * mkstemp(), i.e. end in "XXXXXX". The X string will
1210 * be modified to form the name of a file that didn't exist.
1211 * The string should be in the GLib file name encoding. Most importantly,
1212 * on Windows it should be in UTF-8.
1214 * Return value: A file handle (as from open()) to the file
1215 * opened for reading and writing. The file is opened in binary mode
1216 * on platforms where there is a difference. The file handle should be
1217 * closed with close(). In case of errors, -1 is returned.
1220 g_mkstemp (gchar *tmpl)
1223 return mkstemp (tmpl);
1228 static const char letters[] =
1229 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1230 static const int NLETTERS = sizeof (letters) - 1;
1233 static int counter = 0;
1235 len = strlen (tmpl);
1236 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
1242 /* This is where the Xs start. */
1243 XXXXXX = &tmpl[len - 6];
1245 /* Get some more or less random data. */
1246 g_get_current_time (&tv);
1247 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1249 for (count = 0; count < 100; value += 7777, ++count)
1253 /* Fill in the random bits. */
1254 XXXXXX[0] = letters[v % NLETTERS];
1256 XXXXXX[1] = letters[v % NLETTERS];
1258 XXXXXX[2] = letters[v % NLETTERS];
1260 XXXXXX[3] = letters[v % NLETTERS];
1262 XXXXXX[4] = letters[v % NLETTERS];
1264 XXXXXX[5] = letters[v % NLETTERS];
1266 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1267 fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1271 else if (errno != EEXIST)
1272 /* Any other error will apply also to other names we might
1273 * try, and there are 2^32 or so of them, so give up now.
1278 /* We got out of the loop because we ran out of combinations to try. */
1288 /* Binary compatibility version. Not for newly compiled code. */
1291 g_mkstemp (gchar *tmpl)
1296 static const char letters[] =
1297 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1298 static const int NLETTERS = sizeof (letters) - 1;
1301 static int counter = 0;
1303 len = strlen (tmpl);
1304 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
1310 /* This is where the Xs start. */
1311 XXXXXX = &tmpl[len - 6];
1313 /* Get some more or less random data. */
1314 g_get_current_time (&tv);
1315 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1317 for (count = 0; count < 100; value += 7777, ++count)
1321 /* Fill in the random bits. */
1322 XXXXXX[0] = letters[v % NLETTERS];
1324 XXXXXX[1] = letters[v % NLETTERS];
1326 XXXXXX[2] = letters[v % NLETTERS];
1328 XXXXXX[3] = letters[v % NLETTERS];
1330 XXXXXX[4] = letters[v % NLETTERS];
1332 XXXXXX[5] = letters[v % NLETTERS];
1334 /* This is the backward compatibility system codepage version,
1335 * thus use normal open().
1337 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1341 else if (errno != EEXIST)
1342 /* Any other error will apply also to other names we might
1343 * try, and there are 2^32 or so of them, so give up now.
1348 /* We got out of the loop because we ran out of combinations to try. */
1357 * @tmpl: Template for file name, as in g_mkstemp(), basename only
1358 * @name_used: location to store actual name used
1359 * @error: return location for a #GError
1361 * Opens a file for writing in the preferred directory for temporary
1362 * files (as returned by g_get_tmp_dir()).
1364 * @tmpl should be a string in the GLib file name encoding ending with
1365 * six 'X' characters, as the parameter to g_mkstemp() (or mkstemp()).
1366 * However, unlike these functions, the template should only be a
1367 * basename, no directory components are allowed. If template is
1368 * %NULL, a default template is used.
1370 * Note that in contrast to g_mkstemp() (and mkstemp())
1371 * @tmpl is not modified, and might thus be a read-only literal string.
1373 * The actual name used is returned in @name_used if non-%NULL. This
1374 * string should be freed with g_free() when not needed any longer.
1375 * The returned name is in the GLib file name encoding.
1377 * Return value: A file handle (as from open()) to
1378 * the file opened for reading and writing. The file is opened in binary
1379 * mode on platforms where there is a difference. The file handle should be
1380 * closed with close(). In case of errors, -1 is returned
1381 * and @error will be set.
1384 g_file_open_tmp (const gchar *tmpl,
1397 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1399 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1403 gchar *display_tmpl = g_filename_display_name (tmpl);
1410 G_FILE_ERROR_FAILED,
1411 _("Template '%s' invalid, should not contain a '%s'"),
1413 g_free (display_tmpl);
1418 if (strlen (tmpl) < 6 ||
1419 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
1421 gchar *display_tmpl = g_filename_display_name (tmpl);
1424 G_FILE_ERROR_FAILED,
1425 _("Template '%s' doesn't end with XXXXXX"),
1427 g_free (display_tmpl);
1431 tmpdir = g_get_tmp_dir ();
1433 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1436 sep = G_DIR_SEPARATOR_S;
1438 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1440 retval = g_mkstemp (fulltemplate);
1444 int save_errno = errno;
1445 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1449 g_file_error_from_errno (save_errno),
1450 _("Failed to create file '%s': %s"),
1451 display_fulltemplate, g_strerror (save_errno));
1452 g_free (display_fulltemplate);
1453 g_free (fulltemplate);
1458 *name_used = fulltemplate;
1460 g_free (fulltemplate);
1467 #undef g_file_open_tmp
1469 /* Binary compatibility version. Not for newly compiled code. */
1472 g_file_open_tmp (const gchar *tmpl,
1476 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1477 gchar *utf8_name_used;
1480 if (utf8_tmpl == NULL)
1483 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1489 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1491 g_free (utf8_name_used);
1499 g_build_pathv (const gchar *separator,
1500 const gchar *first_element,
1504 gint separator_len = strlen (separator);
1505 gboolean is_first = TRUE;
1506 gboolean have_leading = FALSE;
1507 const gchar *single_element = NULL;
1508 const gchar *next_element;
1509 const gchar *last_trailing = NULL;
1511 result = g_string_new (NULL);
1513 next_element = first_element;
1517 const gchar *element;
1523 element = next_element;
1524 next_element = va_arg (args, gchar *);
1529 /* Ignore empty elements */
1538 strncmp (start, separator, separator_len) == 0)
1539 start += separator_len;
1542 end = start + strlen (start);
1546 while (end >= start + separator_len &&
1547 strncmp (end - separator_len, separator, separator_len) == 0)
1548 end -= separator_len;
1550 last_trailing = end;
1551 while (last_trailing >= element + separator_len &&
1552 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1553 last_trailing -= separator_len;
1557 /* If the leading and trailing separator strings are in the
1558 * same element and overlap, the result is exactly that element
1560 if (last_trailing <= start)
1561 single_element = element;
1563 g_string_append_len (result, element, start - element);
1564 have_leading = TRUE;
1567 single_element = NULL;
1574 g_string_append (result, separator);
1576 g_string_append_len (result, start, end - start);
1582 g_string_free (result, TRUE);
1583 return g_strdup (single_element);
1588 g_string_append (result, last_trailing);
1590 return g_string_free (result, FALSE);
1596 * @separator: a string used to separator the elements of the path.
1597 * @first_element: the first element in the path
1598 * @Varargs: remaining elements in path, terminated by %NULL
1600 * Creates a path from a series of elements using @separator as the
1601 * separator between elements. At the boundary between two elements,
1602 * any trailing occurrences of separator in the first element, or
1603 * leading occurrences of separator in the second element are removed
1604 * and exactly one copy of the separator is inserted.
1606 * Empty elements are ignored.
1608 * The number of leading copies of the separator on the result is
1609 * the same as the number of leading copies of the separator on
1610 * the first non-empty element.
1612 * The number of trailing copies of the separator on the result is
1613 * the same as the number of trailing copies of the separator on
1614 * the last non-empty element. (Determination of the number of
1615 * trailing copies is done without stripping leading copies, so
1616 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1617 * has 1 trailing copy.)
1619 * However, if there is only a single non-empty element, and there
1620 * are no characters in that element not part of the leading or
1621 * trailing separators, then the result is exactly the original value
1624 * Other than for determination of the number of leading and trailing
1625 * copies of the separator, elements consisting only of copies
1626 * of the separator are ignored.
1628 * Return value: a newly-allocated string that must be freed with g_free().
1631 g_build_path (const gchar *separator,
1632 const gchar *first_element,
1638 g_return_val_if_fail (separator != NULL, NULL);
1640 va_start (args, first_element);
1641 str = g_build_pathv (separator, first_element, args);
1649 * @first_element: the first element in the path
1650 * @Varargs: remaining elements in path, terminated by %NULL
1652 * Creates a filename from a series of elements using the correct
1653 * separator for filenames.
1655 * On Unix, this function behaves identically to <literal>g_build_path
1656 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1658 * On Windows, it takes into account that either the backslash
1659 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1660 * as separator in filenames, but otherwise behaves as on Unix. When
1661 * file pathname separators need to be inserted, the one that last
1662 * previously occurred in the parameters (reading from left to right)
1665 * No attempt is made to force the resulting filename to be an absolute
1666 * path. If the first element is a relative path, the result will
1667 * be a relative path.
1669 * Return value: a newly-allocated string that must be freed with g_free().
1672 g_build_filename (const gchar *first_element,
1679 va_start (args, first_element);
1680 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
1685 /* Code copied from g_build_pathv(), and modifed to use two
1686 * alternative single-character separators.
1690 gboolean is_first = TRUE;
1691 gboolean have_leading = FALSE;
1692 const gchar *single_element = NULL;
1693 const gchar *next_element;
1694 const gchar *last_trailing = NULL;
1695 gchar current_separator = '\\';
1697 va_start (args, first_element);
1699 result = g_string_new (NULL);
1701 next_element = first_element;
1705 const gchar *element;
1711 element = next_element;
1712 next_element = va_arg (args, gchar *);
1717 /* Ignore empty elements */
1726 (*start == '\\' || *start == '/'))
1728 current_separator = *start;
1733 end = start + strlen (start);
1737 while (end >= start + 1 &&
1738 (end[-1] == '\\' || end[-1] == '/'))
1740 current_separator = end[-1];
1744 last_trailing = end;
1745 while (last_trailing >= element + 1 &&
1746 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1751 /* If the leading and trailing separator strings are in the
1752 * same element and overlap, the result is exactly that element
1754 if (last_trailing <= start)
1755 single_element = element;
1757 g_string_append_len (result, element, start - element);
1758 have_leading = TRUE;
1761 single_element = NULL;
1768 g_string_append_len (result, ¤t_separator, 1);
1770 g_string_append_len (result, start, end - start);
1778 g_string_free (result, TRUE);
1779 return g_strdup (single_element);
1784 g_string_append (result, last_trailing);
1786 return g_string_free (result, FALSE);
1793 * @filename: the symbolic link
1794 * @error: return location for a #GError
1796 * Reads the contents of the symbolic link @filename like the POSIX
1797 * readlink() function. The returned string is in the encoding used
1798 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1800 * Returns: A newly allocated string with the contents of the symbolic link,
1801 * or %NULL if an error occurred.
1806 g_file_read_link (const gchar *filename,
1809 #ifdef HAVE_READLINK
1815 buffer = g_malloc (size);
1819 read_size = readlink (filename, buffer, size);
1820 if (read_size < 0) {
1821 int save_errno = errno;
1822 gchar *display_filename = g_filename_display_name (filename);
1827 g_file_error_from_errno (save_errno),
1828 _("Failed to read the symbolic link '%s': %s"),
1830 g_strerror (save_errno));
1831 g_free (display_filename);
1836 if (read_size < size)
1838 buffer[read_size] = 0;
1843 buffer = g_realloc (buffer, size);
1849 _("Symbolic links not supported"));
1855 #define __G_FILEUTILS_C__
1856 #include "galiasdef.c"