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>
45 #endif /* G_OS_WIN32 */
62 * @filename: a filename to test in the GLib file name encoding
63 * @test: bitfield of #GFileTest flags
65 * Returns %TRUE if any of the tests in the bitfield @test are
66 * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS |
67 * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists;
68 * the check whether it's a directory doesn't matter since the existence
69 * test is %TRUE. With the current set of available tests, there's no point
70 * passing in more than one test at a time.
72 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
73 * so for a symbolic link to a regular file g_file_test() will return
74 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
76 * Note, that for a dangling symbolic link g_file_test() will return
77 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
79 * You should never use g_file_test() to test whether it is safe
80 * to perform an operation, because there is always the possibility
81 * of the condition changing before you actually perform the operation.
82 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
83 * to know whether it is is safe to write to a file without being
84 * tricked into writing into a different location. It doesn't work!
86 * <informalexample><programlisting>
87 * /* DON'T DO THIS */
88 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) {
89 * fd = g_open (filename, O_WRONLY);
90 * /* write to fd */
92 * </programlisting></informalexample>
94 * Another thing to note is that %G_FILE_TEST_EXISTS and
95 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
96 * system call. This usually doesn't matter, but if your program
97 * is setuid or setgid it means that these tests will give you
98 * the answer for the real user ID and group ID, rather than the
99 * effective user ID and group ID.
101 * On Windows, there are no symlinks, so testing for
102 * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
103 * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
104 * its name indicates that it is executable, checking for well-known
105 * extensions and those listed in the %PATHEXT environment variable.
107 * Return value: whether a test was %TRUE
110 g_file_test (const gchar *filename,
114 /* stuff missing in std vc6 api */
115 # ifndef INVALID_FILE_ATTRIBUTES
116 # define INVALID_FILE_ATTRIBUTES -1
118 # ifndef FILE_ATTRIBUTE_DEVICE
119 # define FILE_ATTRIBUTE_DEVICE 64
123 if (G_WIN32_HAVE_WIDECHAR_API ())
125 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
127 if (wfilename == NULL)
130 attributes = GetFileAttributesW (wfilename);
136 gchar *cpfilename = g_locale_from_utf8 (filename, -1, NULL, NULL, NULL);
138 if (cpfilename == NULL)
141 attributes = GetFileAttributesA (cpfilename);
146 if (attributes == INVALID_FILE_ATTRIBUTES)
149 if (test & G_FILE_TEST_EXISTS)
152 if (test & G_FILE_TEST_IS_REGULAR)
153 return (attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0;
155 if (test & G_FILE_TEST_IS_DIR)
156 return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
158 if (test & G_FILE_TEST_IS_EXECUTABLE)
160 const gchar *lastdot = strrchr (filename, '.');
161 const gchar *pathext = NULL, *p;
167 if (stricmp (lastdot, ".exe") == 0 ||
168 stricmp (lastdot, ".cmd") == 0 ||
169 stricmp (lastdot, ".bat") == 0 ||
170 stricmp (lastdot, ".com") == 0)
173 /* Check if it is one of the types listed in %PATHEXT% */
175 pathext = g_getenv ("PATHEXT");
179 pathext = g_utf8_casefold (pathext, -1);
181 lastdot = g_utf8_casefold (lastdot, -1);
182 extlen = strlen (lastdot);
187 const gchar *q = strchr (p, ';');
190 if (extlen == q - p &&
191 memcmp (lastdot, p, extlen) == 0)
193 g_free ((gchar *) pathext);
194 g_free ((gchar *) lastdot);
203 g_free ((gchar *) pathext);
204 g_free ((gchar *) lastdot);
210 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
213 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
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.
224 test &= ~G_FILE_TEST_IS_EXECUTABLE;
226 if (test & G_FILE_TEST_IS_SYMLINK)
230 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
234 if (test & (G_FILE_TEST_IS_REGULAR |
236 G_FILE_TEST_IS_EXECUTABLE))
240 if (stat (filename, &s) == 0)
242 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
245 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
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)))
266 /* Binary compatibility version. Not for newly compiled code. */
269 g_file_test (const gchar *filename,
272 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
275 if (utf8_filename == NULL)
278 retval = g_file_test_utf8 (utf8_filename, test);
280 g_free (utf8_filename);
288 g_file_error_quark (void)
292 q = g_quark_from_static_string ("g-file-error-quark");
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
313 g_file_error_from_errno (gint err_no)
319 return G_FILE_ERROR_EXIST;
325 return G_FILE_ERROR_ISDIR;
331 return G_FILE_ERROR_ACCES;
337 return G_FILE_ERROR_NAMETOOLONG;
343 return G_FILE_ERROR_NOENT;
349 return G_FILE_ERROR_NOTDIR;
355 return G_FILE_ERROR_NXIO;
361 return G_FILE_ERROR_NODEV;
367 return G_FILE_ERROR_ROFS;
373 return G_FILE_ERROR_TXTBSY;
379 return G_FILE_ERROR_FAULT;
385 return G_FILE_ERROR_LOOP;
391 return G_FILE_ERROR_NOSPC;
397 return G_FILE_ERROR_NOMEM;
403 return G_FILE_ERROR_MFILE;
409 return G_FILE_ERROR_NFILE;
415 return G_FILE_ERROR_BADF;
421 return G_FILE_ERROR_INVAL;
427 return G_FILE_ERROR_PIPE;
433 return G_FILE_ERROR_AGAIN;
439 return G_FILE_ERROR_INTR;
445 return G_FILE_ERROR_IO;
451 return G_FILE_ERROR_PERM;
457 return G_FILE_ERROR_NOSYS;
462 return G_FILE_ERROR_FAILED;
468 get_contents_stdio (const gchar *display_filename,
477 size_t total_bytes = 0;
478 size_t total_allocated = 0;
481 g_assert (f != NULL);
487 bytes = fread (buf, 1, sizeof (buf), f);
490 while ((total_bytes + bytes + 1) > total_allocated)
493 total_allocated *= 2;
495 total_allocated = MIN (bytes + 1, sizeof (buf));
497 tmp = g_try_realloc (str, total_allocated);
504 _("Could not allocate %lu bytes to read file \"%s\""),
505 (gulong) total_allocated,
518 g_file_error_from_errno (save_errno),
519 _("Error reading file '%s': %s"),
521 g_strerror (save_errno));
526 memcpy (str + total_bytes, buf, bytes);
527 total_bytes += bytes;
532 if (total_allocated == 0)
533 str = g_new (gchar, 1);
535 str[total_bytes] = '\0';
538 *length = total_bytes;
555 get_contents_regfile (const gchar *display_filename,
556 struct stat *stat_buf,
567 size = stat_buf->st_size;
569 alloc_size = size + 1;
570 buf = g_try_malloc (alloc_size);
577 _("Could not allocate %lu bytes to read file \"%s\""),
585 while (bytes_read < size)
589 rc = read (fd, buf + bytes_read, size - bytes_read);
595 int save_errno = errno;
600 g_file_error_from_errno (save_errno),
601 _("Failed to read from file '%s': %s"),
603 g_strerror (save_errno));
614 buf[bytes_read] = '\0';
617 *length = bytes_read;
633 get_contents_posix (const gchar *filename,
638 struct stat stat_buf;
640 gchar *display_filename = g_filename_display_name (filename);
642 /* O_BINARY useful on Cygwin */
643 fd = open (filename, O_RDONLY|O_BINARY);
647 int save_errno = errno;
651 g_file_error_from_errno (save_errno),
652 _("Failed to open file '%s': %s"),
654 g_strerror (save_errno));
655 g_free (display_filename);
660 /* I don't think this will ever fail, aside from ENOMEM, but. */
661 if (fstat (fd, &stat_buf) < 0)
663 int save_errno = errno;
668 g_file_error_from_errno (save_errno),
669 _("Failed to get attributes of file '%s': fstat() failed: %s"),
671 g_strerror (save_errno));
672 g_free (display_filename);
677 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
679 gboolean retval = get_contents_regfile (display_filename,
685 g_free (display_filename);
694 f = fdopen (fd, "r");
698 int save_errno = errno;
702 g_file_error_from_errno (save_errno),
703 _("Failed to open file '%s': fdopen() failed: %s"),
705 g_strerror (save_errno));
706 g_free (display_filename);
711 retval = get_contents_stdio (display_filename, f, contents, length, error);
712 g_free (display_filename);
718 #else /* G_OS_WIN32 */
721 get_contents_win32 (const gchar *filename,
728 gchar *display_filename = g_filename_display_name (filename);
731 f = g_fopen (filename, "rb");
738 g_file_error_from_errno (save_errno),
739 _("Failed to open file '%s': %s"),
741 g_strerror (save_errno));
742 g_free (display_filename);
747 retval = get_contents_stdio (display_filename, f, contents, length, error);
748 g_free (display_filename);
756 * g_file_get_contents:
757 * @filename: name of a file to read contents from, in the GLib file name encoding
758 * @contents: location to store an allocated string
759 * @length: location to store length in bytes of the contents, or %NULL
760 * @error: return location for a #GError, or %NULL
762 * Reads an entire file into allocated memory, with good error
765 * If the call was successful, it returns %TRUE and sets @contents to the file
766 * contents and @length to the length of the file contents in bytes. The string
767 * stored in @contents will be nul-terminated, so for text files you can pass
768 * %NULL for the @length argument. If the call was not successful, it returns
769 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
770 * codes are those in the #GFileError enumeration. In the error case,
771 * @contents is set to %NULL and @length is set to zero.
773 * Return value: %TRUE on success, %FALSE if an error occurred
776 g_file_get_contents (const gchar *filename,
781 g_return_val_if_fail (filename != NULL, FALSE);
782 g_return_val_if_fail (contents != NULL, FALSE);
789 return get_contents_win32 (filename, contents, length, error);
791 return get_contents_posix (filename, contents, length, error);
797 #undef g_file_get_contents
799 /* Binary compatibility version. Not for newly compiled code. */
802 g_file_get_contents (const gchar *filename,
807 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
810 if (utf8_filename == NULL)
813 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
815 g_free (utf8_filename);
823 rename_file (const char *old_name,
824 const char *new_name,
828 if (g_rename (old_name, new_name) == -1)
830 int save_errno = errno;
831 gchar *display_old_name = g_filename_display_name (old_name);
832 gchar *display_new_name = g_filename_display_name (new_name);
836 g_file_error_from_errno (save_errno),
837 _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
840 g_strerror (save_errno));
842 g_free (display_old_name);
843 g_free (display_new_name);
852 set_umask_permissions (int fd,
860 /* All of this function is just to work around the fact that
861 * there is no way to get the umask without changing it.
863 * We can't just change-and-reset the umask because that would
864 * lead to a race condition if another thread tried to change
865 * the umask in between the getting and the setting of the umask.
866 * So we have to do the whole thing in a child process.
879 g_file_error_from_errno (save_errno),
880 _("Could not change file mode: fork() failed: %s"),
881 g_strerror (save_errno));
888 mode_t mask = umask (0666);
891 if (fchmod (fd, 0666 & ~mask) == -1)
896 return TRUE; /* To quiet gcc */
904 if (waitpid (pid, &status, 0) == -1)
910 g_file_error_from_errno (save_errno),
911 _("Could not change file mode: waitpid() failed: %s"),
912 g_strerror (save_errno));
917 if (WIFEXITED (status))
919 save_errno = WEXITSTATUS (status);
929 g_file_error_from_errno (save_errno),
930 _("Could not change file mode: chmod() failed: %s"),
931 g_strerror (save_errno));
936 else if (WIFSIGNALED (status))
941 _("Could not change file mode: Child terminated by signal: %s"),
942 g_strsignal (WTERMSIG (status)));
948 /* This shouldn't happen */
952 _("Could not change file mode: Child terminated abnormally"));
960 write_to_temp_file (const gchar *contents,
962 const gchar *template,
974 tmp_name = g_strdup_printf ("%s.XXXXXX", template);
977 fd = g_mkstemp (tmp_name);
978 display_name = g_filename_display_name (tmp_name);
985 g_file_error_from_errno (save_errno),
986 _("Failed to create file '%s': %s"),
987 display_name, g_strerror (save_errno));
992 if (!set_umask_permissions (fd, err))
1001 file = fdopen (fd, "wb");
1007 g_file_error_from_errno (save_errno),
1008 _("Failed to open file '%s' for writing: fdopen() failed: %s"),
1010 g_strerror (save_errno));
1013 g_unlink (tmp_name);
1024 n_written = fwrite (contents, 1, length, file);
1026 if (n_written < length)
1032 g_file_error_from_errno (save_errno),
1033 _("Failed to write file '%s': fwrite() failed: %s"),
1035 g_strerror (save_errno));
1038 g_unlink (tmp_name);
1045 if (fclose (file) == EOF)
1051 g_file_error_from_errno (save_errno),
1052 _("Failed to close file '%s': fclose() failed: %s"),
1054 g_strerror (save_errno));
1056 g_unlink (tmp_name);
1061 retval = g_strdup (tmp_name);
1065 g_free (display_name);
1072 * @filename: name of a file to write @contents to, in the GLib file name
1074 * @contents: string to write to the file
1075 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1076 * @error: return location for a #GError, or %NULL
1078 * Writes all of @contents to a file named @filename, with good error checking.
1079 * If a file called @filename already exists it will be overwritten.
1081 * This write is atomic in the sense that it is first written to a temporary
1082 * file which is then renamed to the final name. Notes:
1085 * On Unix, if @filename already exists hard links to @filename will break.
1086 * Also since the file is recreated, existing permissions, access control
1087 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1088 * the link itself will be replaced, not the linked file.
1091 * On Windows renaming a file will not remove an existing file with the
1092 * new name, so on Windows there is a race condition between the existing
1093 * file being removed and the temporary file being renamed.
1096 * On Windows there is no way to remove a file that is open to some
1097 * process, or mapped into memory. Thus, this function will fail if
1098 * @filename already exists and is open.
1102 * If the call was sucessful, it returns %TRUE. If the call was not successful,
1103 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1104 * Possible error codes are those in the #GFileError enumeration.
1106 * Return value: %TRUE on success, %FALSE if an error occurred
1111 g_file_replace (const gchar *filename,
1112 const gchar *contents,
1116 gchar *tmp_filename;
1118 GError *rename_error = NULL;
1120 g_return_val_if_fail (filename != NULL, FALSE);
1121 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1122 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1123 g_return_val_if_fail (length >= -1, FALSE);
1126 length = strlen (contents);
1128 tmp_filename = write_to_temp_file (contents, length, filename, error);
1136 if (!rename_file (tmp_filename, filename, &rename_error))
1140 g_unlink (tmp_filename);
1141 g_propagate_error (error, rename_error);
1145 #else /* G_OS_WIN32 */
1147 /* Renaming failed, but on Windows this may just mean
1148 * the file already exists. So if the target file
1149 * exists, try deleting it and do the rename again.
1151 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1153 g_unlink (tmp_filename);
1154 g_propagate_error (error, rename_error);
1159 g_error_free (rename_error);
1161 if (g_unlink (filename) == -1)
1163 gchar *display_filename = g_filename_display_name (filename);
1165 int save_errno = errno;
1169 g_file_error_from_errno (save_errno),
1170 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1172 g_strerror (save_errno));
1174 g_free (display_filename);
1175 g_unlink (tmp_filename);
1180 if (!rename_file (tmp_filename, filename, error))
1182 g_unlink (tmp_filename);
1193 g_free (tmp_filename);
1198 * mkstemp() implementation is from the GNU C library.
1199 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1203 * @tmpl: template filename
1205 * Opens a temporary file. See the mkstemp() documentation
1206 * on most UNIX-like systems. This is a portability wrapper, which simply calls
1207 * mkstemp() on systems that have it, and implements
1208 * it in GLib otherwise.
1210 * The parameter is a string that should match the rules for
1211 * mkstemp(), i.e. end in "XXXXXX". The X string will
1212 * be modified to form the name of a file that didn't exist.
1213 * The string should be in the GLib file name encoding. Most importantly,
1214 * on Windows it should be in UTF-8.
1216 * Return value: A file handle (as from open()) to the file
1217 * opened for reading and writing. The file is opened in binary mode
1218 * on platforms where there is a difference. The file handle should be
1219 * closed with close(). In case of errors, -1 is returned.
1222 g_mkstemp (gchar *tmpl)
1225 return mkstemp (tmpl);
1230 static const char letters[] =
1231 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1232 static const int NLETTERS = sizeof (letters) - 1;
1235 static int counter = 0;
1237 len = strlen (tmpl);
1238 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
1244 /* This is where the Xs start. */
1245 XXXXXX = &tmpl[len - 6];
1247 /* Get some more or less random data. */
1248 g_get_current_time (&tv);
1249 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1251 for (count = 0; count < 100; value += 7777, ++count)
1255 /* Fill in the random bits. */
1256 XXXXXX[0] = letters[v % NLETTERS];
1258 XXXXXX[1] = letters[v % NLETTERS];
1260 XXXXXX[2] = letters[v % NLETTERS];
1262 XXXXXX[3] = letters[v % NLETTERS];
1264 XXXXXX[4] = letters[v % NLETTERS];
1266 XXXXXX[5] = letters[v % NLETTERS];
1268 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1269 fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1273 else if (errno != EEXIST)
1274 /* Any other error will apply also to other names we might
1275 * try, and there are 2^32 or so of them, so give up now.
1280 /* We got out of the loop because we ran out of combinations to try. */
1290 /* Binary compatibility version. Not for newly compiled code. */
1293 g_mkstemp (gchar *tmpl)
1298 static const char letters[] =
1299 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1300 static const int NLETTERS = sizeof (letters) - 1;
1303 static int counter = 0;
1305 len = strlen (tmpl);
1306 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
1312 /* This is where the Xs start. */
1313 XXXXXX = &tmpl[len - 6];
1315 /* Get some more or less random data. */
1316 g_get_current_time (&tv);
1317 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1319 for (count = 0; count < 100; value += 7777, ++count)
1323 /* Fill in the random bits. */
1324 XXXXXX[0] = letters[v % NLETTERS];
1326 XXXXXX[1] = letters[v % NLETTERS];
1328 XXXXXX[2] = letters[v % NLETTERS];
1330 XXXXXX[3] = letters[v % NLETTERS];
1332 XXXXXX[4] = letters[v % NLETTERS];
1334 XXXXXX[5] = letters[v % NLETTERS];
1336 /* This is the backward compatibility system codepage version,
1337 * thus use normal open().
1339 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1343 else if (errno != EEXIST)
1344 /* Any other error will apply also to other names we might
1345 * try, and there are 2^32 or so of them, so give up now.
1350 /* We got out of the loop because we ran out of combinations to try. */
1359 * @tmpl: Template for file name, as in g_mkstemp(), basename only
1360 * @name_used: location to store actual name used
1361 * @error: return location for a #GError
1363 * Opens a file for writing in the preferred directory for temporary
1364 * files (as returned by g_get_tmp_dir()).
1366 * @tmpl should be a string in the GLib file name encoding ending with
1367 * six 'X' characters, as the parameter to g_mkstemp() (or mkstemp()).
1368 * However, unlike these functions, the template should only be a
1369 * basename, no directory components are allowed. If template is
1370 * %NULL, a default template is used.
1372 * Note that in contrast to g_mkstemp() (and mkstemp())
1373 * @tmpl is not modified, and might thus be a read-only literal string.
1375 * The actual name used is returned in @name_used if non-%NULL. This
1376 * string should be freed with g_free() when not needed any longer.
1377 * The returned name is in the GLib file name encoding.
1379 * Return value: A file handle (as from open()) to
1380 * the file opened for reading and writing. The file is opened in binary
1381 * mode on platforms where there is a difference. The file handle should be
1382 * closed with close(). In case of errors, -1 is returned
1383 * and @error will be set.
1386 g_file_open_tmp (const gchar *tmpl,
1399 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1401 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1405 gchar *display_tmpl = g_filename_display_name (tmpl);
1412 G_FILE_ERROR_FAILED,
1413 _("Template '%s' invalid, should not contain a '%s'"),
1415 g_free (display_tmpl);
1420 if (strlen (tmpl) < 6 ||
1421 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
1423 gchar *display_tmpl = g_filename_display_name (tmpl);
1426 G_FILE_ERROR_FAILED,
1427 _("Template '%s' doesn't end with XXXXXX"),
1429 g_free (display_tmpl);
1433 tmpdir = g_get_tmp_dir ();
1435 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1438 sep = G_DIR_SEPARATOR_S;
1440 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1442 retval = g_mkstemp (fulltemplate);
1446 int save_errno = errno;
1447 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1451 g_file_error_from_errno (save_errno),
1452 _("Failed to create file '%s': %s"),
1453 display_fulltemplate, g_strerror (save_errno));
1454 g_free (display_fulltemplate);
1455 g_free (fulltemplate);
1460 *name_used = fulltemplate;
1462 g_free (fulltemplate);
1469 #undef g_file_open_tmp
1471 /* Binary compatibility version. Not for newly compiled code. */
1474 g_file_open_tmp (const gchar *tmpl,
1478 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1479 gchar *utf8_name_used;
1482 if (utf8_tmpl == NULL)
1485 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1491 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1493 g_free (utf8_name_used);
1501 g_build_pathv (const gchar *separator,
1502 const gchar *first_element,
1506 gint separator_len = strlen (separator);
1507 gboolean is_first = TRUE;
1508 gboolean have_leading = FALSE;
1509 const gchar *single_element = NULL;
1510 const gchar *next_element;
1511 const gchar *last_trailing = NULL;
1513 result = g_string_new (NULL);
1515 next_element = first_element;
1519 const gchar *element;
1525 element = next_element;
1526 next_element = va_arg (args, gchar *);
1531 /* Ignore empty elements */
1540 strncmp (start, separator, separator_len) == 0)
1541 start += separator_len;
1544 end = start + strlen (start);
1548 while (end >= start + separator_len &&
1549 strncmp (end - separator_len, separator, separator_len) == 0)
1550 end -= separator_len;
1552 last_trailing = end;
1553 while (last_trailing >= element + separator_len &&
1554 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1555 last_trailing -= separator_len;
1559 /* If the leading and trailing separator strings are in the
1560 * same element and overlap, the result is exactly that element
1562 if (last_trailing <= start)
1563 single_element = element;
1565 g_string_append_len (result, element, start - element);
1566 have_leading = TRUE;
1569 single_element = NULL;
1576 g_string_append (result, separator);
1578 g_string_append_len (result, start, end - start);
1584 g_string_free (result, TRUE);
1585 return g_strdup (single_element);
1590 g_string_append (result, last_trailing);
1592 return g_string_free (result, FALSE);
1598 * @separator: a string used to separator the elements of the path.
1599 * @first_element: the first element in the path
1600 * @Varargs: remaining elements in path, terminated by %NULL
1602 * Creates a path from a series of elements using @separator as the
1603 * separator between elements. At the boundary between two elements,
1604 * any trailing occurrences of separator in the first element, or
1605 * leading occurrences of separator in the second element are removed
1606 * and exactly one copy of the separator is inserted.
1608 * Empty elements are ignored.
1610 * The number of leading copies of the separator on the result is
1611 * the same as the number of leading copies of the separator on
1612 * the first non-empty element.
1614 * The number of trailing copies of the separator on the result is
1615 * the same as the number of trailing copies of the separator on
1616 * the last non-empty element. (Determination of the number of
1617 * trailing copies is done without stripping leading copies, so
1618 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1619 * has 1 trailing copy.)
1621 * However, if there is only a single non-empty element, and there
1622 * are no characters in that element not part of the leading or
1623 * trailing separators, then the result is exactly the original value
1626 * Other than for determination of the number of leading and trailing
1627 * copies of the separator, elements consisting only of copies
1628 * of the separator are ignored.
1630 * Return value: a newly-allocated string that must be freed with g_free().
1633 g_build_path (const gchar *separator,
1634 const gchar *first_element,
1640 g_return_val_if_fail (separator != NULL, NULL);
1642 va_start (args, first_element);
1643 str = g_build_pathv (separator, first_element, args);
1651 * @first_element: the first element in the path
1652 * @Varargs: remaining elements in path, terminated by %NULL
1654 * Creates a filename from a series of elements using the correct
1655 * separator for filenames.
1657 * On Unix, this function behaves identically to <literal>g_build_path
1658 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1660 * On Windows, it takes into account that either the backslash
1661 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1662 * as separator in filenames, but otherwise behaves as on Unix. When
1663 * file pathname separators need to be inserted, the one that last
1664 * previously occurred in the parameters (reading from left to right)
1667 * No attempt is made to force the resulting filename to be an absolute
1668 * path. If the first element is a relative path, the result will
1669 * be a relative path.
1671 * Return value: a newly-allocated string that must be freed with g_free().
1674 g_build_filename (const gchar *first_element,
1681 va_start (args, first_element);
1682 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
1687 /* Code copied from g_build_pathv(), and modifed to use two
1688 * alternative single-character separators.
1692 gboolean is_first = TRUE;
1693 gboolean have_leading = FALSE;
1694 const gchar *single_element = NULL;
1695 const gchar *next_element;
1696 const gchar *last_trailing = NULL;
1697 gchar current_separator = '\\';
1699 va_start (args, first_element);
1701 result = g_string_new (NULL);
1703 next_element = first_element;
1707 const gchar *element;
1713 element = next_element;
1714 next_element = va_arg (args, gchar *);
1719 /* Ignore empty elements */
1728 (*start == '\\' || *start == '/'))
1730 current_separator = *start;
1735 end = start + strlen (start);
1739 while (end >= start + 1 &&
1740 (end[-1] == '\\' || end[-1] == '/'))
1742 current_separator = end[-1];
1746 last_trailing = end;
1747 while (last_trailing >= element + 1 &&
1748 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1753 /* If the leading and trailing separator strings are in the
1754 * same element and overlap, the result is exactly that element
1756 if (last_trailing <= start)
1757 single_element = element;
1759 g_string_append_len (result, element, start - element);
1760 have_leading = TRUE;
1763 single_element = NULL;
1770 g_string_append_len (result, ¤t_separator, 1);
1772 g_string_append_len (result, start, end - start);
1780 g_string_free (result, TRUE);
1781 return g_strdup (single_element);
1786 g_string_append (result, last_trailing);
1788 return g_string_free (result, FALSE);
1795 * @filename: the symbolic link
1796 * @error: return location for a #GError
1798 * Reads the contents of the symbolic link @filename like the POSIX
1799 * readlink() function. The returned string is in the encoding used
1800 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1802 * Returns: A newly allocated string with the contents of the symbolic link,
1803 * or %NULL if an error occurred.
1808 g_file_read_link (const gchar *filename,
1811 #ifdef HAVE_READLINK
1817 buffer = g_malloc (size);
1821 read_size = readlink (filename, buffer, size);
1822 if (read_size < 0) {
1823 int save_errno = errno;
1824 gchar *display_filename = g_filename_display_name (filename);
1829 g_file_error_from_errno (save_errno),
1830 _("Failed to read the symbolic link '%s': %s"),
1832 g_strerror (save_errno));
1833 g_free (display_filename);
1838 if (read_size < size)
1840 buffer[read_size] = 0;
1845 buffer = g_realloc (buffer, size);
1851 _("Symbolic links not supported"));
1857 #define __G_FILEUTILS_C__
1858 #include "galiasdef.c"