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;
477 g_assert (f != NULL);
483 bytes = fread (buf, 1, sizeof (buf), f);
486 while ((total_bytes + bytes + 1) > total_allocated)
489 total_allocated *= 2;
491 total_allocated = MIN (bytes + 1, sizeof (buf));
493 str = g_try_realloc (str, total_allocated);
500 _("Could not allocate %lu bytes to read file \"%s\""),
501 (gulong) total_allocated,
512 g_file_error_from_errno (save_errno),
513 _("Error reading file '%s': %s"),
515 g_strerror (save_errno));
520 memcpy (str + total_bytes, buf, bytes);
521 total_bytes += bytes;
526 if (total_bytes == 0)
527 str = g_new (gchar, 1);
529 str[total_bytes] = '\0';
532 *length = total_bytes;
549 get_contents_regfile (const gchar *display_filename,
550 struct stat *stat_buf,
561 size = stat_buf->st_size;
563 alloc_size = size + 1;
564 buf = g_try_malloc (alloc_size);
571 _("Could not allocate %lu bytes to read file \"%s\""),
579 while (bytes_read < size)
583 rc = read (fd, buf + bytes_read, size - bytes_read);
589 int save_errno = errno;
594 g_file_error_from_errno (save_errno),
595 _("Failed to read from file '%s': %s"),
597 g_strerror (save_errno));
608 buf[bytes_read] = '\0';
611 *length = bytes_read;
627 get_contents_posix (const gchar *filename,
632 struct stat stat_buf;
634 gchar *display_filename = g_filename_display_name (filename);
636 /* O_BINARY useful on Cygwin */
637 fd = open (filename, O_RDONLY|O_BINARY);
641 int save_errno = errno;
645 g_file_error_from_errno (save_errno),
646 _("Failed to open file '%s': %s"),
648 g_strerror (save_errno));
649 g_free (display_filename);
654 /* I don't think this will ever fail, aside from ENOMEM, but. */
655 if (fstat (fd, &stat_buf) < 0)
657 int save_errno = errno;
662 g_file_error_from_errno (save_errno),
663 _("Failed to get attributes of file '%s': fstat() failed: %s"),
665 g_strerror (save_errno));
666 g_free (display_filename);
671 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
673 gboolean retval = get_contents_regfile (display_filename,
679 g_free (display_filename);
688 f = fdopen (fd, "r");
692 int save_errno = errno;
696 g_file_error_from_errno (save_errno),
697 _("Failed to open file '%s': fdopen() failed: %s"),
699 g_strerror (save_errno));
700 g_free (display_filename);
705 retval = get_contents_stdio (display_filename, f, contents, length, error);
706 g_free (display_filename);
712 #else /* G_OS_WIN32 */
715 get_contents_win32 (const gchar *filename,
722 gchar *display_filename = g_filename_display_name (filename);
725 f = g_fopen (filename, "rb");
732 g_file_error_from_errno (save_errno),
733 _("Failed to open file '%s': %s"),
735 g_strerror (save_errno));
736 g_free (display_filename);
741 retval = get_contents_stdio (display_filename, f, contents, length, error);
742 g_free (display_filename);
750 * g_file_get_contents:
751 * @filename: name of a file to read contents from, in the GLib file name encoding
752 * @contents: location to store an allocated string
753 * @length: location to store length in bytes of the contents, or %NULL
754 * @error: return location for a #GError, or %NULL
756 * Reads an entire file into allocated memory, with good error
759 * If the call was successful, it returns %TRUE and sets @contents to the file
760 * contents and @length to the length of the file contents in bytes. The string
761 * stored in @contents will be nul-terminated, so for text files you can pass
762 * %NULL for the @length argument. If the call was not successful, it returns
763 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
764 * codes are those in the #GFileError enumeration. In the error case,
765 * @contents is set to %NULL and @length is set to zero.
767 * Return value: %TRUE on success, %FALSE if an error occurred
770 g_file_get_contents (const gchar *filename,
775 g_return_val_if_fail (filename != NULL, FALSE);
776 g_return_val_if_fail (contents != NULL, FALSE);
783 return get_contents_win32 (filename, contents, length, error);
785 return get_contents_posix (filename, contents, length, error);
791 #undef g_file_get_contents
793 /* Binary compatibility version. Not for newly compiled code. */
796 g_file_get_contents (const gchar *filename,
801 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
804 if (utf8_filename == NULL)
807 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
809 g_free (utf8_filename);
818 rename_file (const char *old_name,
819 const char *new_name,
823 if (g_rename (old_name, new_name) == -1)
825 int save_errno = errno;
826 gchar *display_old_name = g_filename_display_name (old_name);
827 gchar *display_new_name = g_filename_display_name (new_name);
831 g_file_error_from_errno (save_errno),
832 _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
835 g_strerror (save_errno));
837 g_free (display_old_name);
838 g_free (display_new_name);
847 write_to_temp_file (const gchar *contents,
849 const gchar *template,
861 tmp_name = g_strdup_printf ("%s.XXXXXX", template);
864 fd = g_mkstemp (tmp_name);
866 display_name = g_filename_display_name (tmp_name);
872 g_file_error_from_errno (save_errno),
873 _("Failed to create file '%s': %s"),
874 display_name, g_strerror (save_errno));
880 file = fdopen (fd, "wb");
885 g_file_error_from_errno (errno),
886 _("Failed to open file '%s' for writing: fdopen() failed: %s"),
902 n_written = fwrite (contents, 1, length, file);
904 if (n_written < length)
908 g_file_error_from_errno (errno),
909 _("Failed to write file '%s': fwrite() failed: %s"),
921 if (fclose (file) == EOF)
925 g_file_error_from_errno (errno),
926 _("Failed to close file '%s': fclose() failed: %s"),
935 retval = g_strdup (tmp_name);
939 g_free (display_name);
946 * @filename: name of a file to write @contents to, in the GLib file name
948 * @contents: string to write to the file
949 * @length: length of @contents, or -1 if @contents is a nul-terminated string
950 * @error: return location for a #GError, or %NULL
952 * Writes all of @contents to a file named @filename, with good error checking.
953 * If a file called @filename already exists it will be overwritten.
955 * This write is atomic in the sense that it is first written to a temporary
956 * file which is then renamed to the final name. Notes:
959 * On Unix, if @filename already exists hard links to @filename will break.
960 * Also since the file is recreated, existing permissions, access control
961 * lists, metadata etc. may be lost. If @filename is a symbolic link,
962 * the link itself will be replaced, not the linked file.
965 * On Windows renaming a file will not remove an existing file with the
966 * new name, so on Windows there is a race condition between the existing
967 * file being removed and the temporary file being renamed.
970 * On Windows there is no way to remove a file that is open to some
971 * process, or mapped into memory. Thus, this function will fail if
972 * @filename already exists and is open.
976 * If the call was sucessful, it returns %TRUE. If the call was not successful,
977 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
978 * Possible error codes are those in the #GFileError enumeration.
980 * Return value: %TRUE on success, %FALSE if an error occurred
985 g_file_replace (const gchar *filename,
986 const gchar *contents,
992 GError *rename_error = NULL;
994 g_return_val_if_fail (filename != NULL, FALSE);
995 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
996 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
997 g_return_val_if_fail (length >= -1, FALSE);
1000 length = strlen (contents);
1002 tmp_filename = write_to_temp_file (contents, length, filename, error);
1010 if (!rename_file (tmp_filename, filename, &rename_error))
1014 g_unlink (tmp_filename);
1015 g_propagate_error (error, rename_error);
1019 #else /* G_OS_WIN32 */
1021 /* Renaming failed, but on Windows this may just mean
1022 * the file already exists. So if the target file
1023 * exists, try deleting it and do the rename again.
1025 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1027 g_unlink (tmp_filename);
1028 g_propagate_error (error, rename_error);
1033 g_error_free (rename_error);
1035 if (g_unlink (filename) == -1)
1037 gchar *display_filename = g_filename_display_name (filename);
1041 g_file_error_from_errno (errno),
1042 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1044 g_strerror (errno));
1046 g_free (display_filename);
1047 g_unlink (tmp_filename);
1052 if (!rename_file (tmp_filename, filename, error))
1054 g_unlink (tmp_filename);
1065 g_free (tmp_filename);
1070 * mkstemp() implementation is from the GNU C library.
1071 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1075 * @tmpl: template filename
1077 * Opens a temporary file. See the mkstemp() documentation
1078 * on most UNIX-like systems. This is a portability wrapper, which simply calls
1079 * mkstemp() on systems that have it, and implements
1080 * it in GLib otherwise.
1082 * The parameter is a string that should match the rules for
1083 * mkstemp(), i.e. end in "XXXXXX". The X string will
1084 * be modified to form the name of a file that didn't exist.
1085 * The string should be in the GLib file name encoding. Most importantly,
1086 * on Windows it should be in UTF-8.
1088 * Return value: A file handle (as from open()) to the file
1089 * opened for reading and writing. The file is opened in binary mode
1090 * on platforms where there is a difference. The file handle should be
1091 * closed with close(). In case of errors, -1 is returned.
1094 g_mkstemp (gchar *tmpl)
1097 return mkstemp (tmpl);
1102 static const char letters[] =
1103 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1104 static const int NLETTERS = sizeof (letters) - 1;
1107 static int counter = 0;
1109 len = strlen (tmpl);
1110 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
1116 /* This is where the Xs start. */
1117 XXXXXX = &tmpl[len - 6];
1119 /* Get some more or less random data. */
1120 g_get_current_time (&tv);
1121 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1123 for (count = 0; count < 100; value += 7777, ++count)
1127 /* Fill in the random bits. */
1128 XXXXXX[0] = letters[v % NLETTERS];
1130 XXXXXX[1] = letters[v % NLETTERS];
1132 XXXXXX[2] = letters[v % NLETTERS];
1134 XXXXXX[3] = letters[v % NLETTERS];
1136 XXXXXX[4] = letters[v % NLETTERS];
1138 XXXXXX[5] = letters[v % NLETTERS];
1140 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1141 fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1145 else if (errno != EEXIST)
1146 /* Any other error will apply also to other names we might
1147 * try, and there are 2^32 or so of them, so give up now.
1152 /* We got out of the loop because we ran out of combinations to try. */
1162 /* Binary compatibility version. Not for newly compiled code. */
1165 g_mkstemp (gchar *tmpl)
1170 static const char letters[] =
1171 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1172 static const int NLETTERS = sizeof (letters) - 1;
1175 static int counter = 0;
1177 len = strlen (tmpl);
1178 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
1184 /* This is where the Xs start. */
1185 XXXXXX = &tmpl[len - 6];
1187 /* Get some more or less random data. */
1188 g_get_current_time (&tv);
1189 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1191 for (count = 0; count < 100; value += 7777, ++count)
1195 /* Fill in the random bits. */
1196 XXXXXX[0] = letters[v % NLETTERS];
1198 XXXXXX[1] = letters[v % NLETTERS];
1200 XXXXXX[2] = letters[v % NLETTERS];
1202 XXXXXX[3] = letters[v % NLETTERS];
1204 XXXXXX[4] = letters[v % NLETTERS];
1206 XXXXXX[5] = letters[v % NLETTERS];
1208 /* This is the backward compatibility system codepage version,
1209 * thus use normal open().
1211 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1215 else if (errno != EEXIST)
1216 /* Any other error will apply also to other names we might
1217 * try, and there are 2^32 or so of them, so give up now.
1222 /* We got out of the loop because we ran out of combinations to try. */
1231 * @tmpl: Template for file name, as in g_mkstemp(), basename only
1232 * @name_used: location to store actual name used
1233 * @error: return location for a #GError
1235 * Opens a file for writing in the preferred directory for temporary
1236 * files (as returned by g_get_tmp_dir()).
1238 * @tmpl should be a string in the GLib file name encoding ending with
1239 * six 'X' characters, as the parameter to g_mkstemp() (or mkstemp()).
1240 * However, unlike these functions, the template should only be a
1241 * basename, no directory components are allowed. If template is
1242 * %NULL, a default template is used.
1244 * Note that in contrast to g_mkstemp() (and mkstemp())
1245 * @tmpl is not modified, and might thus be a read-only literal string.
1247 * The actual name used is returned in @name_used if non-%NULL. This
1248 * string should be freed with g_free() when not needed any longer.
1249 * The returned name is in the GLib file name encoding.
1251 * Return value: A file handle (as from open()) to
1252 * the file opened for reading and writing. The file is opened in binary
1253 * mode on platforms where there is a difference. The file handle should be
1254 * closed with close(). In case of errors, -1 is returned
1255 * and @error will be set.
1258 g_file_open_tmp (const gchar *tmpl,
1271 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1273 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1277 gchar *display_tmpl = g_filename_display_name (tmpl);
1284 G_FILE_ERROR_FAILED,
1285 _("Template '%s' invalid, should not contain a '%s'"),
1287 g_free (display_tmpl);
1292 if (strlen (tmpl) < 6 ||
1293 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
1295 gchar *display_tmpl = g_filename_display_name (tmpl);
1298 G_FILE_ERROR_FAILED,
1299 _("Template '%s' doesn't end with XXXXXX"),
1301 g_free (display_tmpl);
1305 tmpdir = g_get_tmp_dir ();
1307 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1310 sep = G_DIR_SEPARATOR_S;
1312 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1314 retval = g_mkstemp (fulltemplate);
1318 int save_errno = errno;
1319 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1323 g_file_error_from_errno (save_errno),
1324 _("Failed to create file '%s': %s"),
1325 display_fulltemplate, g_strerror (save_errno));
1326 g_free (display_fulltemplate);
1327 g_free (fulltemplate);
1332 *name_used = fulltemplate;
1334 g_free (fulltemplate);
1341 #undef g_file_open_tmp
1343 /* Binary compatibility version. Not for newly compiled code. */
1346 g_file_open_tmp (const gchar *tmpl,
1350 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1351 gchar *utf8_name_used;
1354 if (utf8_tmpl == NULL)
1357 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1363 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1365 g_free (utf8_name_used);
1373 g_build_pathv (const gchar *separator,
1374 const gchar *first_element,
1378 gint separator_len = strlen (separator);
1379 gboolean is_first = TRUE;
1380 gboolean have_leading = FALSE;
1381 const gchar *single_element = NULL;
1382 const gchar *next_element;
1383 const gchar *last_trailing = NULL;
1385 result = g_string_new (NULL);
1387 next_element = first_element;
1391 const gchar *element;
1397 element = next_element;
1398 next_element = va_arg (args, gchar *);
1403 /* Ignore empty elements */
1412 strncmp (start, separator, separator_len) == 0)
1413 start += separator_len;
1416 end = start + strlen (start);
1420 while (end >= start + separator_len &&
1421 strncmp (end - separator_len, separator, separator_len) == 0)
1422 end -= separator_len;
1424 last_trailing = end;
1425 while (last_trailing >= element + separator_len &&
1426 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1427 last_trailing -= separator_len;
1431 /* If the leading and trailing separator strings are in the
1432 * same element and overlap, the result is exactly that element
1434 if (last_trailing <= start)
1435 single_element = element;
1437 g_string_append_len (result, element, start - element);
1438 have_leading = TRUE;
1441 single_element = NULL;
1448 g_string_append (result, separator);
1450 g_string_append_len (result, start, end - start);
1456 g_string_free (result, TRUE);
1457 return g_strdup (single_element);
1462 g_string_append (result, last_trailing);
1464 return g_string_free (result, FALSE);
1470 * @separator: a string used to separator the elements of the path.
1471 * @first_element: the first element in the path
1472 * @Varargs: remaining elements in path, terminated by %NULL
1474 * Creates a path from a series of elements using @separator as the
1475 * separator between elements. At the boundary between two elements,
1476 * any trailing occurrences of separator in the first element, or
1477 * leading occurrences of separator in the second element are removed
1478 * and exactly one copy of the separator is inserted.
1480 * Empty elements are ignored.
1482 * The number of leading copies of the separator on the result is
1483 * the same as the number of leading copies of the separator on
1484 * the first non-empty element.
1486 * The number of trailing copies of the separator on the result is
1487 * the same as the number of trailing copies of the separator on
1488 * the last non-empty element. (Determination of the number of
1489 * trailing copies is done without stripping leading copies, so
1490 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1491 * has 1 trailing copy.)
1493 * However, if there is only a single non-empty element, and there
1494 * are no characters in that element not part of the leading or
1495 * trailing separators, then the result is exactly the original value
1498 * Other than for determination of the number of leading and trailing
1499 * copies of the separator, elements consisting only of copies
1500 * of the separator are ignored.
1502 * Return value: a newly-allocated string that must be freed with g_free().
1505 g_build_path (const gchar *separator,
1506 const gchar *first_element,
1512 g_return_val_if_fail (separator != NULL, NULL);
1514 va_start (args, first_element);
1515 str = g_build_pathv (separator, first_element, args);
1523 * @first_element: the first element in the path
1524 * @Varargs: remaining elements in path, terminated by %NULL
1526 * Creates a filename from a series of elements using the correct
1527 * separator for filenames.
1529 * On Unix, this function behaves identically to <literal>g_build_path
1530 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1532 * On Windows, it takes into account that either the backslash
1533 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1534 * as separator in filenames, but otherwise behaves as on Unix. When
1535 * file pathname separators need to be inserted, the one that last
1536 * previously occurred in the parameters (reading from left to right)
1539 * No attempt is made to force the resulting filename to be an absolute
1540 * path. If the first element is a relative path, the result will
1541 * be a relative path.
1543 * Return value: a newly-allocated string that must be freed with g_free().
1546 g_build_filename (const gchar *first_element,
1553 va_start (args, first_element);
1554 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
1559 /* Code copied from g_build_pathv(), and modifed to use two
1560 * alternative single-character separators.
1564 gboolean is_first = TRUE;
1565 gboolean have_leading = FALSE;
1566 const gchar *single_element = NULL;
1567 const gchar *next_element;
1568 const gchar *last_trailing = NULL;
1569 gchar current_separator = '\\';
1571 va_start (args, first_element);
1573 result = g_string_new (NULL);
1575 next_element = first_element;
1579 const gchar *element;
1585 element = next_element;
1586 next_element = va_arg (args, gchar *);
1591 /* Ignore empty elements */
1600 (*start == '\\' || *start == '/'))
1602 current_separator = *start;
1607 end = start + strlen (start);
1611 while (end >= start + 1 &&
1612 (end[-1] == '\\' || end[-1] == '/'))
1614 current_separator = end[-1];
1618 last_trailing = end;
1619 while (last_trailing >= element + 1 &&
1620 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1625 /* If the leading and trailing separator strings are in the
1626 * same element and overlap, the result is exactly that element
1628 if (last_trailing <= start)
1629 single_element = element;
1631 g_string_append_len (result, element, start - element);
1632 have_leading = TRUE;
1635 single_element = NULL;
1642 g_string_append_len (result, ¤t_separator, 1);
1644 g_string_append_len (result, start, end - start);
1652 g_string_free (result, TRUE);
1653 return g_strdup (single_element);
1658 g_string_append (result, last_trailing);
1660 return g_string_free (result, FALSE);
1667 * @filename: the symbolic link
1668 * @error: return location for a #GError
1670 * Reads the contents of the symbolic link @filename like the POSIX
1671 * readlink() function. The returned string is in the encoding used
1672 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1674 * Returns: A newly allocated string with the contents of the symbolic link,
1675 * or %NULL if an error occurred.
1680 g_file_read_link (const gchar *filename,
1683 #ifdef HAVE_READLINK
1689 buffer = g_malloc (size);
1693 read_size = readlink (filename, buffer, size);
1694 if (read_size < 0) {
1695 int save_errno = errno;
1696 gchar *display_filename = g_filename_display_name (filename);
1701 g_file_error_from_errno (save_errno),
1702 _("Failed to read the symbolic link '%s': %s"),
1704 g_strerror (save_errno));
1705 g_free (display_filename);
1710 if (read_size < size)
1712 buffer[read_size] = 0;
1717 buffer = g_realloc (buffer, size);
1723 _("Symbolic links not supported"));
1729 #define __G_FILEUTILS_C__
1730 #include "galiasdef.c"