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>
42 #endif /* G_OS_WIN32 */
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 * /* DON'T DO THIS */
85 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) {
86 * fd = g_open (filename, O_WRONLY);
87 * /* write to fd */
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
107 g_file_test (const gchar *filename,
111 /* stuff missing in std vc6 api */
112 # ifndef INVALID_FILE_ATTRIBUTES
113 # define INVALID_FILE_ATTRIBUTES -1
115 # ifndef FILE_ATTRIBUTE_DEVICE
116 # define FILE_ATTRIBUTE_DEVICE 64
120 if (G_WIN32_HAVE_WIDECHAR_API ())
122 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
124 if (wfilename == NULL)
127 attributes = GetFileAttributesW (wfilename);
133 gchar *cpfilename = g_locale_from_utf8 (filename, -1, NULL, NULL, NULL);
135 if (cpfilename == NULL)
138 attributes = GetFileAttributesA (cpfilename);
143 if (attributes == INVALID_FILE_ATTRIBUTES)
146 if (test & G_FILE_TEST_EXISTS)
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;
164 if (stricmp (lastdot, ".exe") == 0 ||
165 stricmp (lastdot, ".cmd") == 0 ||
166 stricmp (lastdot, ".bat") == 0 ||
167 stricmp (lastdot, ".com") == 0)
170 /* Check if it is one of the types listed in %PATHEXT% */
172 pathext = g_getenv ("PATHEXT");
176 pathext = g_utf8_casefold (pathext, -1);
178 lastdot = g_utf8_casefold (lastdot, -1);
179 extlen = strlen (lastdot);
184 const gchar *q = strchr (p, ';');
187 if (extlen == q - p &&
188 memcmp (lastdot, p, extlen) == 0)
190 g_free ((gchar *) pathext);
191 g_free ((gchar *) lastdot);
200 g_free ((gchar *) pathext);
201 g_free ((gchar *) lastdot);
207 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
210 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
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.
221 test &= ~G_FILE_TEST_IS_EXECUTABLE;
223 if (test & G_FILE_TEST_IS_SYMLINK)
227 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
231 if (test & (G_FILE_TEST_IS_REGULAR |
233 G_FILE_TEST_IS_EXECUTABLE))
237 if (stat (filename, &s) == 0)
239 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
242 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
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)))
263 /* Binary compatibility version. Not for newly compiled code. */
266 g_file_test (const gchar *filename,
269 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
272 if (utf8_filename == NULL)
275 retval = g_file_test_utf8 (utf8_filename, test);
277 g_free (utf8_filename);
285 g_file_error_quark (void)
289 q = g_quark_from_static_string ("g-file-error-quark");
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
310 g_file_error_from_errno (gint err_no)
316 return G_FILE_ERROR_EXIST;
322 return G_FILE_ERROR_ISDIR;
328 return G_FILE_ERROR_ACCES;
334 return G_FILE_ERROR_NAMETOOLONG;
340 return G_FILE_ERROR_NOENT;
346 return G_FILE_ERROR_NOTDIR;
352 return G_FILE_ERROR_NXIO;
358 return G_FILE_ERROR_NODEV;
364 return G_FILE_ERROR_ROFS;
370 return G_FILE_ERROR_TXTBSY;
376 return G_FILE_ERROR_FAULT;
382 return G_FILE_ERROR_LOOP;
388 return G_FILE_ERROR_NOSPC;
394 return G_FILE_ERROR_NOMEM;
400 return G_FILE_ERROR_MFILE;
406 return G_FILE_ERROR_NFILE;
412 return G_FILE_ERROR_BADF;
418 return G_FILE_ERROR_INVAL;
424 return G_FILE_ERROR_PIPE;
430 return G_FILE_ERROR_AGAIN;
436 return G_FILE_ERROR_INTR;
442 return G_FILE_ERROR_IO;
448 return G_FILE_ERROR_PERM;
454 return G_FILE_ERROR_NOSYS;
459 return G_FILE_ERROR_FAILED;
465 get_contents_stdio (const gchar *display_filename,
474 size_t total_bytes = 0;
475 size_t total_allocated = 0;
478 g_assert (f != NULL);
484 bytes = fread (buf, 1, sizeof (buf), f);
487 while ((total_bytes + bytes + 1) > total_allocated)
490 total_allocated *= 2;
492 total_allocated = MIN (bytes + 1, sizeof (buf));
494 tmp = g_try_realloc (str, total_allocated);
501 _("Could not allocate %lu bytes to read file \"%s\""),
502 (gulong) total_allocated,
515 g_file_error_from_errno (save_errno),
516 _("Error reading file '%s': %s"),
518 g_strerror (save_errno));
523 memcpy (str + total_bytes, buf, bytes);
524 total_bytes += bytes;
529 if (total_allocated == 0)
530 str = g_new (gchar, 1);
532 str[total_bytes] = '\0';
535 *length = total_bytes;
552 get_contents_regfile (const gchar *display_filename,
553 struct stat *stat_buf,
564 size = stat_buf->st_size;
566 alloc_size = size + 1;
567 buf = g_try_malloc (alloc_size);
574 _("Could not allocate %lu bytes to read file \"%s\""),
582 while (bytes_read < size)
586 rc = read (fd, buf + bytes_read, size - bytes_read);
592 int save_errno = errno;
597 g_file_error_from_errno (save_errno),
598 _("Failed to read from file '%s': %s"),
600 g_strerror (save_errno));
611 buf[bytes_read] = '\0';
614 *length = bytes_read;
630 get_contents_posix (const gchar *filename,
635 struct stat stat_buf;
637 gchar *display_filename = g_filename_display_name (filename);
639 /* O_BINARY useful on Cygwin */
640 fd = open (filename, O_RDONLY|O_BINARY);
644 int save_errno = errno;
648 g_file_error_from_errno (save_errno),
649 _("Failed to open file '%s': %s"),
651 g_strerror (save_errno));
652 g_free (display_filename);
657 /* I don't think this will ever fail, aside from ENOMEM, but. */
658 if (fstat (fd, &stat_buf) < 0)
660 int save_errno = errno;
665 g_file_error_from_errno (save_errno),
666 _("Failed to get attributes of file '%s': fstat() failed: %s"),
668 g_strerror (save_errno));
669 g_free (display_filename);
674 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
676 gboolean retval = get_contents_regfile (display_filename,
682 g_free (display_filename);
691 f = fdopen (fd, "r");
695 int save_errno = errno;
699 g_file_error_from_errno (save_errno),
700 _("Failed to open file '%s': fdopen() failed: %s"),
702 g_strerror (save_errno));
703 g_free (display_filename);
708 retval = get_contents_stdio (display_filename, f, contents, length, error);
709 g_free (display_filename);
715 #else /* G_OS_WIN32 */
718 get_contents_win32 (const gchar *filename,
725 gchar *display_filename = g_filename_display_name (filename);
728 f = g_fopen (filename, "rb");
735 g_file_error_from_errno (save_errno),
736 _("Failed to open file '%s': %s"),
738 g_strerror (save_errno));
739 g_free (display_filename);
744 retval = get_contents_stdio (display_filename, f, contents, length, error);
745 g_free (display_filename);
753 * g_file_get_contents:
754 * @filename: name of a file to read contents from, in the GLib file name encoding
755 * @contents: location to store an allocated string
756 * @length: location to store length in bytes of the contents, or %NULL
757 * @error: return location for a #GError, or %NULL
759 * Reads an entire file into allocated memory, with good error
762 * If the call was successful, it returns %TRUE and sets @contents to the file
763 * contents and @length to the length of the file contents in bytes. The string
764 * stored in @contents will be nul-terminated, so for text files you can pass
765 * %NULL for the @length argument. If the call was not successful, it returns
766 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
767 * codes are those in the #GFileError enumeration. In the error case,
768 * @contents is set to %NULL and @length is set to zero.
770 * Return value: %TRUE on success, %FALSE if an error occurred
773 g_file_get_contents (const gchar *filename,
778 g_return_val_if_fail (filename != NULL, FALSE);
779 g_return_val_if_fail (contents != NULL, FALSE);
786 return get_contents_win32 (filename, contents, length, error);
788 return get_contents_posix (filename, contents, length, error);
794 #undef g_file_get_contents
796 /* Binary compatibility version. Not for newly compiled code. */
799 g_file_get_contents (const gchar *filename,
804 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
807 if (utf8_filename == NULL)
810 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
812 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 write_to_temp_file (const gchar *contents,
852 const gchar *template,
864 tmp_name = g_strdup_printf ("%s.XXXXXX", template);
867 fd = g_mkstemp (tmp_name);
869 display_name = g_filename_display_name (tmp_name);
875 g_file_error_from_errno (save_errno),
876 _("Failed to create file '%s': %s"),
877 display_name, g_strerror (save_errno));
883 file = fdopen (fd, "wb");
888 g_file_error_from_errno (errno),
889 _("Failed to open file '%s' for writing: fdopen() failed: %s"),
905 n_written = fwrite (contents, 1, length, file);
907 if (n_written < length)
911 g_file_error_from_errno (errno),
912 _("Failed to write file '%s': fwrite() failed: %s"),
924 if (fclose (file) == EOF)
928 g_file_error_from_errno (errno),
929 _("Failed to close file '%s': fclose() failed: %s"),
938 retval = g_strdup (tmp_name);
942 g_free (display_name);
949 * @filename: name of a file to write @contents to, in the GLib file name
951 * @contents: string to write to the file
952 * @length: length of @contents, or -1 if @contents is a nul-terminated string
953 * @error: return location for a #GError, or %NULL
955 * Writes all of @contents to a file named @filename, with good error checking.
956 * If a file called @filename already exists it will be overwritten.
958 * This write is atomic in the sense that it is first written to a temporary
959 * file which is then renamed to the final name. Notes:
962 * On Unix, if @filename already exists hard links to @filename will break.
963 * Also since the file is recreated, existing permissions, access control
964 * lists, metadata etc. may be lost. If @filename is a symbolic link,
965 * the link itself will be replaced, not the linked file.
968 * On Windows renaming a file will not remove an existing file with the
969 * new name, so on Windows there is a race condition between the existing
970 * file being removed and the temporary file being renamed.
973 * On Windows there is no way to remove a file that is open to some
974 * process, or mapped into memory. Thus, this function will fail if
975 * @filename already exists and is open.
979 * If the call was sucessful, it returns %TRUE. If the call was not successful,
980 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
981 * Possible error codes are those in the #GFileError enumeration.
983 * Return value: %TRUE on success, %FALSE if an error occurred
988 g_file_replace (const gchar *filename,
989 const gchar *contents,
995 GError *rename_error = NULL;
997 g_return_val_if_fail (filename != NULL, FALSE);
998 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
999 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1000 g_return_val_if_fail (length >= -1, FALSE);
1003 length = strlen (contents);
1005 tmp_filename = write_to_temp_file (contents, length, filename, error);
1013 if (!rename_file (tmp_filename, filename, &rename_error))
1017 g_unlink (tmp_filename);
1018 g_propagate_error (error, rename_error);
1022 #else /* G_OS_WIN32 */
1024 /* Renaming failed, but on Windows this may just mean
1025 * the file already exists. So if the target file
1026 * exists, try deleting it and do the rename again.
1028 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1030 g_unlink (tmp_filename);
1031 g_propagate_error (error, rename_error);
1036 g_error_free (rename_error);
1038 if (g_unlink (filename) == -1)
1040 gchar *display_filename = g_filename_display_name (filename);
1044 g_file_error_from_errno (errno),
1045 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1047 g_strerror (errno));
1049 g_free (display_filename);
1050 g_unlink (tmp_filename);
1055 if (!rename_file (tmp_filename, filename, error))
1057 g_unlink (tmp_filename);
1068 g_free (tmp_filename);
1073 * mkstemp() implementation is from the GNU C library.
1074 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1078 * @tmpl: template filename
1080 * Opens a temporary file. See the mkstemp() documentation
1081 * on most UNIX-like systems. This is a portability wrapper, which simply calls
1082 * mkstemp() on systems that have it, and implements
1083 * it in GLib otherwise.
1085 * The parameter is a string that should match the rules for
1086 * mkstemp(), i.e. end in "XXXXXX". The X string will
1087 * be modified to form the name of a file that didn't exist.
1088 * The string should be in the GLib file name encoding. Most importantly,
1089 * on Windows it should be in UTF-8.
1091 * Return value: A file handle (as from open()) to the file
1092 * opened for reading and writing. The file is opened in binary mode
1093 * on platforms where there is a difference. The file handle should be
1094 * closed with close(). In case of errors, -1 is returned.
1097 g_mkstemp (gchar *tmpl)
1100 return mkstemp (tmpl);
1105 static const char letters[] =
1106 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1107 static const int NLETTERS = sizeof (letters) - 1;
1110 static int counter = 0;
1112 len = strlen (tmpl);
1113 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
1119 /* This is where the Xs start. */
1120 XXXXXX = &tmpl[len - 6];
1122 /* Get some more or less random data. */
1123 g_get_current_time (&tv);
1124 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1126 for (count = 0; count < 100; value += 7777, ++count)
1130 /* Fill in the random bits. */
1131 XXXXXX[0] = letters[v % NLETTERS];
1133 XXXXXX[1] = letters[v % NLETTERS];
1135 XXXXXX[2] = letters[v % NLETTERS];
1137 XXXXXX[3] = letters[v % NLETTERS];
1139 XXXXXX[4] = letters[v % NLETTERS];
1141 XXXXXX[5] = letters[v % NLETTERS];
1143 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1144 fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1148 else if (errno != EEXIST)
1149 /* Any other error will apply also to other names we might
1150 * try, and there are 2^32 or so of them, so give up now.
1155 /* We got out of the loop because we ran out of combinations to try. */
1165 /* Binary compatibility version. Not for newly compiled code. */
1168 g_mkstemp (gchar *tmpl)
1173 static const char letters[] =
1174 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1175 static const int NLETTERS = sizeof (letters) - 1;
1178 static int counter = 0;
1180 len = strlen (tmpl);
1181 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
1187 /* This is where the Xs start. */
1188 XXXXXX = &tmpl[len - 6];
1190 /* Get some more or less random data. */
1191 g_get_current_time (&tv);
1192 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1194 for (count = 0; count < 100; value += 7777, ++count)
1198 /* Fill in the random bits. */
1199 XXXXXX[0] = letters[v % NLETTERS];
1201 XXXXXX[1] = letters[v % NLETTERS];
1203 XXXXXX[2] = letters[v % NLETTERS];
1205 XXXXXX[3] = letters[v % NLETTERS];
1207 XXXXXX[4] = letters[v % NLETTERS];
1209 XXXXXX[5] = letters[v % NLETTERS];
1211 /* This is the backward compatibility system codepage version,
1212 * thus use normal open().
1214 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1218 else if (errno != EEXIST)
1219 /* Any other error will apply also to other names we might
1220 * try, and there are 2^32 or so of them, so give up now.
1225 /* We got out of the loop because we ran out of combinations to try. */
1234 * @tmpl: Template for file name, as in g_mkstemp(), basename only
1235 * @name_used: location to store actual name used
1236 * @error: return location for a #GError
1238 * Opens a file for writing in the preferred directory for temporary
1239 * files (as returned by g_get_tmp_dir()).
1241 * @tmpl should be a string in the GLib file name encoding ending with
1242 * six 'X' characters, as the parameter to g_mkstemp() (or mkstemp()).
1243 * However, unlike these functions, the template should only be a
1244 * basename, no directory components are allowed. If template is
1245 * %NULL, a default template is used.
1247 * Note that in contrast to g_mkstemp() (and mkstemp())
1248 * @tmpl is not modified, and might thus be a read-only literal string.
1250 * The actual name used is returned in @name_used if non-%NULL. This
1251 * string should be freed with g_free() when not needed any longer.
1252 * The returned name is in the GLib file name encoding.
1254 * Return value: A file handle (as from open()) to
1255 * the file opened for reading and writing. The file is opened in binary
1256 * mode on platforms where there is a difference. The file handle should be
1257 * closed with close(). In case of errors, -1 is returned
1258 * and @error will be set.
1261 g_file_open_tmp (const gchar *tmpl,
1274 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1276 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1280 gchar *display_tmpl = g_filename_display_name (tmpl);
1287 G_FILE_ERROR_FAILED,
1288 _("Template '%s' invalid, should not contain a '%s'"),
1290 g_free (display_tmpl);
1295 if (strlen (tmpl) < 6 ||
1296 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
1298 gchar *display_tmpl = g_filename_display_name (tmpl);
1301 G_FILE_ERROR_FAILED,
1302 _("Template '%s' doesn't end with XXXXXX"),
1304 g_free (display_tmpl);
1308 tmpdir = g_get_tmp_dir ();
1310 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1313 sep = G_DIR_SEPARATOR_S;
1315 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1317 retval = g_mkstemp (fulltemplate);
1321 int save_errno = errno;
1322 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1326 g_file_error_from_errno (save_errno),
1327 _("Failed to create file '%s': %s"),
1328 display_fulltemplate, g_strerror (save_errno));
1329 g_free (display_fulltemplate);
1330 g_free (fulltemplate);
1335 *name_used = fulltemplate;
1337 g_free (fulltemplate);
1344 #undef g_file_open_tmp
1346 /* Binary compatibility version. Not for newly compiled code. */
1349 g_file_open_tmp (const gchar *tmpl,
1353 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1354 gchar *utf8_name_used;
1357 if (utf8_tmpl == NULL)
1360 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1366 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1368 g_free (utf8_name_used);
1376 g_build_pathv (const gchar *separator,
1377 const gchar *first_element,
1381 gint separator_len = strlen (separator);
1382 gboolean is_first = TRUE;
1383 gboolean have_leading = FALSE;
1384 const gchar *single_element = NULL;
1385 const gchar *next_element;
1386 const gchar *last_trailing = NULL;
1388 result = g_string_new (NULL);
1390 next_element = first_element;
1394 const gchar *element;
1400 element = next_element;
1401 next_element = va_arg (args, gchar *);
1406 /* Ignore empty elements */
1415 strncmp (start, separator, separator_len) == 0)
1416 start += separator_len;
1419 end = start + strlen (start);
1423 while (end >= start + separator_len &&
1424 strncmp (end - separator_len, separator, separator_len) == 0)
1425 end -= separator_len;
1427 last_trailing = end;
1428 while (last_trailing >= element + separator_len &&
1429 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1430 last_trailing -= separator_len;
1434 /* If the leading and trailing separator strings are in the
1435 * same element and overlap, the result is exactly that element
1437 if (last_trailing <= start)
1438 single_element = element;
1440 g_string_append_len (result, element, start - element);
1441 have_leading = TRUE;
1444 single_element = NULL;
1451 g_string_append (result, separator);
1453 g_string_append_len (result, start, end - start);
1459 g_string_free (result, TRUE);
1460 return g_strdup (single_element);
1465 g_string_append (result, last_trailing);
1467 return g_string_free (result, FALSE);
1473 * @separator: a string used to separator the elements of the path.
1474 * @first_element: the first element in the path
1475 * @Varargs: remaining elements in path, terminated by %NULL
1477 * Creates a path from a series of elements using @separator as the
1478 * separator between elements. At the boundary between two elements,
1479 * any trailing occurrences of separator in the first element, or
1480 * leading occurrences of separator in the second element are removed
1481 * and exactly one copy of the separator is inserted.
1483 * Empty elements are ignored.
1485 * The number of leading copies of the separator on the result is
1486 * the same as the number of leading copies of the separator on
1487 * the first non-empty element.
1489 * The number of trailing copies of the separator on the result is
1490 * the same as the number of trailing copies of the separator on
1491 * the last non-empty element. (Determination of the number of
1492 * trailing copies is done without stripping leading copies, so
1493 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1494 * has 1 trailing copy.)
1496 * However, if there is only a single non-empty element, and there
1497 * are no characters in that element not part of the leading or
1498 * trailing separators, then the result is exactly the original value
1501 * Other than for determination of the number of leading and trailing
1502 * copies of the separator, elements consisting only of copies
1503 * of the separator are ignored.
1505 * Return value: a newly-allocated string that must be freed with g_free().
1508 g_build_path (const gchar *separator,
1509 const gchar *first_element,
1515 g_return_val_if_fail (separator != NULL, NULL);
1517 va_start (args, first_element);
1518 str = g_build_pathv (separator, first_element, args);
1526 * @first_element: the first element in the path
1527 * @Varargs: remaining elements in path, terminated by %NULL
1529 * Creates a filename from a series of elements using the correct
1530 * separator for filenames.
1532 * On Unix, this function behaves identically to <literal>g_build_path
1533 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1535 * On Windows, it takes into account that either the backslash
1536 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1537 * as separator in filenames, but otherwise behaves as on Unix. When
1538 * file pathname separators need to be inserted, the one that last
1539 * previously occurred in the parameters (reading from left to right)
1542 * No attempt is made to force the resulting filename to be an absolute
1543 * path. If the first element is a relative path, the result will
1544 * be a relative path.
1546 * Return value: a newly-allocated string that must be freed with g_free().
1549 g_build_filename (const gchar *first_element,
1556 va_start (args, first_element);
1557 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
1562 /* Code copied from g_build_pathv(), and modifed to use two
1563 * alternative single-character separators.
1567 gboolean is_first = TRUE;
1568 gboolean have_leading = FALSE;
1569 const gchar *single_element = NULL;
1570 const gchar *next_element;
1571 const gchar *last_trailing = NULL;
1572 gchar current_separator = '\\';
1574 va_start (args, first_element);
1576 result = g_string_new (NULL);
1578 next_element = first_element;
1582 const gchar *element;
1588 element = next_element;
1589 next_element = va_arg (args, gchar *);
1594 /* Ignore empty elements */
1603 (*start == '\\' || *start == '/'))
1605 current_separator = *start;
1610 end = start + strlen (start);
1614 while (end >= start + 1 &&
1615 (end[-1] == '\\' || end[-1] == '/'))
1617 current_separator = end[-1];
1621 last_trailing = end;
1622 while (last_trailing >= element + 1 &&
1623 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1628 /* If the leading and trailing separator strings are in the
1629 * same element and overlap, the result is exactly that element
1631 if (last_trailing <= start)
1632 single_element = element;
1634 g_string_append_len (result, element, start - element);
1635 have_leading = TRUE;
1638 single_element = NULL;
1645 g_string_append_len (result, ¤t_separator, 1);
1647 g_string_append_len (result, start, end - start);
1655 g_string_free (result, TRUE);
1656 return g_strdup (single_element);
1661 g_string_append (result, last_trailing);
1663 return g_string_free (result, FALSE);
1670 * @filename: the symbolic link
1671 * @error: return location for a #GError
1673 * Reads the contents of the symbolic link @filename like the POSIX
1674 * readlink() function. The returned string is in the encoding used
1675 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1677 * Returns: A newly allocated string with the contents of the symbolic link,
1678 * or %NULL if an error occurred.
1683 g_file_read_link (const gchar *filename,
1686 #ifdef HAVE_READLINK
1692 buffer = g_malloc (size);
1696 read_size = readlink (filename, buffer, size);
1697 if (read_size < 0) {
1698 int save_errno = errno;
1699 gchar *display_filename = g_filename_display_name (filename);
1704 g_file_error_from_errno (save_errno),
1705 _("Failed to read the symbolic link '%s': %s"),
1707 g_strerror (save_errno));
1708 g_free (display_filename);
1713 if (read_size < size)
1715 buffer[read_size] = 0;
1720 buffer = g_realloc (buffer, size);
1726 _("Symbolic links not supported"));
1732 #define __G_FILEUTILS_C__
1733 #include "galiasdef.c"