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.
35 #include <sys/types.h>
42 #endif /* G_OS_WIN32 */
57 * @filename: a filename to test in the GLib file name encoding
58 * @test: bitfield of #GFileTest flags
60 * Returns %TRUE if any of the tests in the bitfield @test are
61 * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS |
62 * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists;
63 * the check whether it's a directory doesn't matter since the existence
64 * test is %TRUE. With the current set of available tests, there's no point
65 * passing in more than one test at a time.
67 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
68 * so for a symbolic link to a regular file g_file_test() will return
69 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
71 * Note, that for a dangling symbolic link g_file_test() will return
72 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
74 * You should never use g_file_test() to test whether it is safe
75 * to perform an operation, because there is always the possibility
76 * of the condition changing before you actually perform the operation.
77 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
78 * to know whether it is is safe to write to a file without being
79 * tricked into writing into a different location. It doesn't work!
81 * <informalexample><programlisting>
82 * /* DON'T DO THIS */
83 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) {
84 * fd = g_open (filename, O_WRONLY);
85 * /* write to fd */
87 * </programlisting></informalexample>
89 * Another thing to note is that %G_FILE_TEST_EXISTS and
90 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
91 * system call. This usually doesn't matter, but if your program
92 * is setuid or setgid it means that these tests will give you
93 * the answer for the real user ID and group ID, rather than the
94 * effective user ID and group ID.
96 * On Windows, there are no symlinks, so testing for
97 * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
98 * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
99 * its name indicates that it is executable, checking for well-known
100 * extensions and those listed in the %PATHEXT environment variable.
102 * Return value: whether a test was %TRUE
105 g_file_test (const gchar *filename,
111 if (G_WIN32_HAVE_WIDECHAR_API ())
113 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
115 if (wfilename == NULL)
118 attributes = GetFileAttributesW (wfilename);
124 gchar *cpfilename = g_locale_from_utf8 (filename, -1, NULL, NULL, NULL);
126 if (cpfilename == NULL)
129 attributes = GetFileAttributesA (cpfilename);
134 if (attributes == INVALID_FILE_ATTRIBUTES)
137 if (test & G_FILE_TEST_EXISTS)
140 if (test & G_FILE_TEST_IS_REGULAR)
141 return (attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0;
143 if (test & G_FILE_TEST_IS_DIR)
144 return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
146 if (test & G_FILE_TEST_IS_EXECUTABLE)
148 const gchar *lastdot = strrchr (filename, '.');
149 gchar *pathext = NULL, *tem, *p;
155 if (stricmp (lastdot, ".exe") == 0 ||
156 stricmp (lastdot, ".cmd") == 0 ||
157 stricmp (lastdot, ".bat") == 0 ||
158 stricmp (lastdot, ".com") == 0)
161 /* Check if it is one of the types listed in %PATHEXT% */
163 /* Perhaps unfortunately, g_getenv() doesn't return UTF-8, but
164 * system codepage. And _wgetenv() isn't useful either, as the C
165 * runtime just keeps system codepage versions of the
166 * environment variables in applications that aren't built
167 * specially. So use GetEnvironmentVariableW().
169 if (G_WIN32_HAVE_WIDECHAR_API ())
171 wchar_t dummy[2], *wvar;
174 len = GetEnvironmentVariableW (L"PATHEXT", dummy, 2);
179 wvar = g_new (wchar_t, len);
181 if (GetEnvironmentVariableW (L"PATHEXT", wvar, len) == len - 1)
182 pathext = g_utf16_to_utf8 (wvar, -1, NULL, NULL, NULL);
188 gchar dummy[2], *cpvar;
191 len = GetEnvironmentVariableA ("PATHEXT", dummy, 2);
196 cpvar = g_new (gchar, len);
198 if (GetEnvironmentVariableA ("PATHEXT", cpvar, len) == len - 1)
199 pathext = g_locale_to_utf8 (cpvar, -1, NULL, NULL, NULL);
208 pathext = g_utf8_casefold (pathext, -1);
211 lastdot = g_utf8_casefold (lastdot, -1);
212 extlen = strlen (lastdot);
217 gchar *q = strchr (p, ';');
220 if (extlen == q - p &&
221 memcmp (lastdot, p, extlen) == 0)
224 g_free ((gchar *) lastdot);
234 g_free ((gchar *) lastdot);
240 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
243 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
248 /* For root, on some POSIX systems, access (filename, X_OK)
249 * will succeed even if no executable bits are set on the
250 * file. We fall through to a stat test to avoid that.
254 test &= ~G_FILE_TEST_IS_EXECUTABLE;
256 if (test & G_FILE_TEST_IS_SYMLINK)
260 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
264 if (test & (G_FILE_TEST_IS_REGULAR |
266 G_FILE_TEST_IS_EXECUTABLE))
270 if (stat (filename, &s) == 0)
272 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
275 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
278 /* The extra test for root when access (file, X_OK) succeeds.
280 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
281 ((s.st_mode & S_IXOTH) ||
282 (s.st_mode & S_IXUSR) ||
283 (s.st_mode & S_IXGRP)))
296 /* Binary compatibility version. Not for newly compiled code. */
299 g_file_test (const gchar *filename,
302 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
305 if (utf8_filename == NULL)
308 retval = g_file_test_utf8 (utf8_filename, test);
310 g_free (utf8_filename);
318 g_file_error_quark (void)
322 q = g_quark_from_static_string ("g-file-error-quark");
328 * g_file_error_from_errno:
329 * @err_no: an "errno" value
331 * Gets a #GFileError constant based on the passed-in @errno.
332 * For example, if you pass in %EEXIST this function returns
333 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
334 * assume that all #GFileError values will exist.
336 * Normally a #GFileError value goes into a #GError returned
337 * from a function that manipulates files. So you would use
338 * g_file_error_from_errno() when constructing a #GError.
340 * Return value: #GFileError corresponding to the given @errno
343 g_file_error_from_errno (gint err_no)
349 return G_FILE_ERROR_EXIST;
355 return G_FILE_ERROR_ISDIR;
361 return G_FILE_ERROR_ACCES;
367 return G_FILE_ERROR_NAMETOOLONG;
373 return G_FILE_ERROR_NOENT;
379 return G_FILE_ERROR_NOTDIR;
385 return G_FILE_ERROR_NXIO;
391 return G_FILE_ERROR_NODEV;
397 return G_FILE_ERROR_ROFS;
403 return G_FILE_ERROR_TXTBSY;
409 return G_FILE_ERROR_FAULT;
415 return G_FILE_ERROR_LOOP;
421 return G_FILE_ERROR_NOSPC;
427 return G_FILE_ERROR_NOMEM;
433 return G_FILE_ERROR_MFILE;
439 return G_FILE_ERROR_NFILE;
445 return G_FILE_ERROR_BADF;
451 return G_FILE_ERROR_INVAL;
457 return G_FILE_ERROR_PIPE;
463 return G_FILE_ERROR_AGAIN;
469 return G_FILE_ERROR_INTR;
475 return G_FILE_ERROR_IO;
481 return G_FILE_ERROR_PERM;
487 return G_FILE_ERROR_NOSYS;
492 return G_FILE_ERROR_FAILED;
498 get_contents_stdio (const gchar *display_filename,
508 size_t total_allocated;
510 g_assert (f != NULL);
512 #define STARTING_ALLOC 64
515 total_allocated = STARTING_ALLOC;
516 str = g_malloc (STARTING_ALLOC);
520 bytes = fread (buf, 1, 2048, f);
522 while ((total_bytes + bytes + 1) > total_allocated)
524 total_allocated *= 2;
525 str = g_try_realloc (str, total_allocated);
532 _("Could not allocate %lu bytes to read file \"%s\""),
533 (gulong) total_allocated,
544 g_file_error_from_errno (errno),
545 _("Error reading file '%s': %s"),
552 memcpy (str + total_bytes, buf, bytes);
553 total_bytes += bytes;
558 str[total_bytes] = '\0';
561 *length = total_bytes;
578 get_contents_regfile (const gchar *display_filename,
579 struct stat *stat_buf,
590 size = stat_buf->st_size;
592 alloc_size = size + 1;
593 buf = g_try_malloc (alloc_size);
600 _("Could not allocate %lu bytes to read file \"%s\""),
608 while (bytes_read < size)
612 rc = read (fd, buf + bytes_read, size - bytes_read);
621 g_file_error_from_errno (errno),
622 _("Failed to read from file '%s': %s"),
635 buf[bytes_read] = '\0';
638 *length = bytes_read;
654 get_contents_posix (const gchar *filename,
659 struct stat stat_buf;
661 gchar *display_filename = g_filename_display_name (filename);
663 /* O_BINARY useful on Cygwin */
664 fd = open (filename, O_RDONLY|O_BINARY);
670 g_file_error_from_errno (errno),
671 _("Failed to open file '%s': %s"),
674 g_free (display_filename);
679 /* I don't think this will ever fail, aside from ENOMEM, but. */
680 if (fstat (fd, &stat_buf) < 0)
685 g_file_error_from_errno (errno),
686 _("Failed to get attributes of file '%s': fstat() failed: %s"),
689 g_free (display_filename);
694 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
696 gboolean retval = get_contents_regfile (display_filename,
702 g_free (display_filename);
711 f = fdopen (fd, "r");
717 g_file_error_from_errno (errno),
718 _("Failed to open file '%s': fdopen() failed: %s"),
721 g_free (display_filename);
726 retval = get_contents_stdio (display_filename, f, contents, length, error);
727 g_free (display_filename);
733 #else /* G_OS_WIN32 */
736 get_contents_win32 (const gchar *filename,
743 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
744 gchar *display_filename = g_filename_display_name (filename);
746 f = _wfopen (wfilename, L"rb");
753 g_file_error_from_errno (errno),
754 _("Failed to open file '%s': %s"),
757 g_free (display_filename);
762 retval = get_contents_stdio (display_filename, f, contents, length, error);
763 g_free (display_filename);
771 * g_file_get_contents:
772 * @filename: name of a file to read contents from, in the GLib file name encoding
773 * @contents: location to store an allocated string
774 * @length: location to store length in bytes of the contents
775 * @error: return location for a #GError
777 * Reads an entire file into allocated memory, with good error
778 * checking. If @error is set, %FALSE is returned, and @contents is set
779 * to %NULL. If %TRUE is returned, @error will not be set, and @contents
780 * will be set to the file contents. The string stored in @contents
781 * will be nul-terminated, so for text files you can pass %NULL for the
782 * @length argument. The error domain is #G_FILE_ERROR. Possible
783 * error codes are those in the #GFileError enumeration.
785 * Return value: %TRUE on success, %FALSE if error is set
788 g_file_get_contents (const gchar *filename,
793 g_return_val_if_fail (filename != NULL, FALSE);
794 g_return_val_if_fail (contents != NULL, FALSE);
801 return get_contents_win32 (filename, contents, length, error);
803 return get_contents_posix (filename, contents, length, error);
809 #undef g_file_get_contents
811 /* Binary compatibility version. Not for newly compiled code. */
814 g_file_get_contents (const gchar *filename,
819 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
822 if (utf8_filename == NULL)
825 retval = g_file_get_contents (utf8_filename, contents, length, error);
827 g_free (utf8_filename);
835 * mkstemp() implementation is from the GNU C library.
836 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
840 * @tmpl: template filename
842 * Opens a temporary file. See the mkstemp() documentation
843 * on most UNIX-like systems. This is a portability wrapper, which simply calls
844 * mkstemp() on systems that have it, and implements
845 * it in GLib otherwise.
847 * The parameter is a string that should match the rules for
848 * mkstemp(), i.e. end in "XXXXXX". The X string will
849 * be modified to form the name of a file that didn't exist.
850 * The string should be in the GLib file name encoding. Most importantly,
851 * on Windows it should be in UTF-8.
853 * Return value: A file handle (as from open()) to the file
854 * opened for reading and writing. The file is opened in binary mode
855 * on platforms where there is a difference. The file handle should be
856 * closed with close(). In case of errors, -1 is returned.
859 g_mkstemp (gchar *tmpl)
862 return mkstemp (tmpl);
867 static const char letters[] =
868 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
869 static const int NLETTERS = sizeof (letters) - 1;
872 static int counter = 0;
875 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
878 /* This is where the Xs start. */
879 XXXXXX = &tmpl[len - 6];
881 /* Get some more or less random data. */
882 g_get_current_time (&tv);
883 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
885 for (count = 0; count < 100; value += 7777, ++count)
889 /* Fill in the random bits. */
890 XXXXXX[0] = letters[v % NLETTERS];
892 XXXXXX[1] = letters[v % NLETTERS];
894 XXXXXX[2] = letters[v % NLETTERS];
896 XXXXXX[3] = letters[v % NLETTERS];
898 XXXXXX[4] = letters[v % NLETTERS];
900 XXXXXX[5] = letters[v % NLETTERS];
902 /* tmpl is in UTF-8 on Windows, thus use g_open() */
903 fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
907 else if (errno != EEXIST)
908 /* Any other error will apply also to other names we might
909 * try, and there are 2^32 or so of them, so give up now.
914 /* We got out of the loop because we ran out of combinations to try. */
923 /* Binary compatibility version. Not for newly compiled code. */
926 g_mkstemp (gchar *tmpl)
931 static const char letters[] =
932 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
933 static const int NLETTERS = sizeof (letters) - 1;
936 static int counter = 0;
939 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
942 /* This is where the Xs start. */
943 XXXXXX = &tmpl[len - 6];
945 /* Get some more or less random data. */
946 g_get_current_time (&tv);
947 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
949 for (count = 0; count < 100; value += 7777, ++count)
953 /* Fill in the random bits. */
954 XXXXXX[0] = letters[v % NLETTERS];
956 XXXXXX[1] = letters[v % NLETTERS];
958 XXXXXX[2] = letters[v % NLETTERS];
960 XXXXXX[3] = letters[v % NLETTERS];
962 XXXXXX[4] = letters[v % NLETTERS];
964 XXXXXX[5] = letters[v % NLETTERS];
966 /* This is the backward compatibility system codepage version,
967 * thus use normal open().
969 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
973 else if (errno != EEXIST)
974 /* Any other error will apply also to other names we might
975 * try, and there are 2^32 or so of them, so give up now.
980 /* We got out of the loop because we ran out of combinations to try. */
988 * @tmpl: Template for file name, as in g_mkstemp(), basename only
989 * @name_used: location to store actual name used
990 * @error: return location for a #GError
992 * Opens a file for writing in the preferred directory for temporary
993 * files (as returned by g_get_tmp_dir()).
995 * @tmpl should be a string in the GLib file name encoding ending with
996 * six 'X' characters, as the parameter to g_mkstemp() (or mkstemp()).
997 * However, unlike these functions, the template should only be a
998 * basename, no directory components are allowed. If template is
999 * %NULL, a default template is used.
1001 * Note that in contrast to g_mkstemp() (and mkstemp())
1002 * @tmpl is not modified, and might thus be a read-only literal string.
1004 * The actual name used is returned in @name_used if non-%NULL. This
1005 * string should be freed with g_free() when not needed any longer.
1006 * The returned name is in the GLib file name encoding.
1008 * Return value: A file handle (as from open()) to
1009 * the file opened for reading and writing. The file is opened in binary
1010 * mode on platforms where there is a difference. The file handle should be
1011 * closed with close(). In case of errors, -1 is returned
1012 * and @error will be set.
1015 g_file_open_tmp (const gchar *tmpl,
1028 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1030 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1034 gchar *display_tmpl = g_filename_display_name (tmpl);
1041 G_FILE_ERROR_FAILED,
1042 _("Template '%s' invalid, should not contain a '%s'"),
1044 g_free (display_tmpl);
1049 if (strlen (tmpl) < 6 ||
1050 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
1052 gchar *display_tmpl = g_filename_display_name (tmpl);
1055 G_FILE_ERROR_FAILED,
1056 _("Template '%s' doesn't end with XXXXXX"),
1058 g_free (display_tmpl);
1062 tmpdir = g_get_tmp_dir ();
1064 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1067 sep = G_DIR_SEPARATOR_S;
1069 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1071 retval = g_mkstemp (fulltemplate);
1075 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1078 g_file_error_from_errno (errno),
1079 _("Failed to create file '%s': %s"),
1080 display_fulltemplate, g_strerror (errno));
1081 g_free (display_fulltemplate);
1082 g_free (fulltemplate);
1087 *name_used = fulltemplate;
1089 g_free (fulltemplate);
1096 #undef g_file_open_tmp
1098 /* Binary compatibility version. Not for newly compiled code. */
1101 g_file_open_tmp (const gchar *tmpl,
1105 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1106 gchar *utf8_name_used;
1109 if (utf8_tmpl == NULL)
1112 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1118 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1120 g_free (utf8_name_used);
1128 g_build_pathv (const gchar *separator,
1129 const gchar *first_element,
1133 gint separator_len = strlen (separator);
1134 gboolean is_first = TRUE;
1135 gboolean have_leading = FALSE;
1136 const gchar *single_element = NULL;
1137 const gchar *next_element;
1138 const gchar *last_trailing = NULL;
1140 result = g_string_new (NULL);
1142 next_element = first_element;
1146 const gchar *element;
1152 element = next_element;
1153 next_element = va_arg (args, gchar *);
1158 /* Ignore empty elements */
1167 strncmp (start, separator, separator_len) == 0)
1168 start += separator_len;
1171 end = start + strlen (start);
1175 while (end >= start + separator_len &&
1176 strncmp (end - separator_len, separator, separator_len) == 0)
1177 end -= separator_len;
1179 last_trailing = end;
1180 while (last_trailing >= element + separator_len &&
1181 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1182 last_trailing -= separator_len;
1186 /* If the leading and trailing separator strings are in the
1187 * same element and overlap, the result is exactly that element
1189 if (last_trailing <= start)
1190 single_element = element;
1192 g_string_append_len (result, element, start - element);
1193 have_leading = TRUE;
1196 single_element = NULL;
1203 g_string_append (result, separator);
1205 g_string_append_len (result, start, end - start);
1211 g_string_free (result, TRUE);
1212 return g_strdup (single_element);
1217 g_string_append (result, last_trailing);
1219 return g_string_free (result, FALSE);
1225 * @separator: a string used to separator the elements of the path.
1226 * @first_element: the first element in the path
1227 * @Varargs: remaining elements in path, terminated by %NULL
1229 * Creates a path from a series of elements using @separator as the
1230 * separator between elements. At the boundary between two elements,
1231 * any trailing occurrences of separator in the first element, or
1232 * leading occurrences of separator in the second element are removed
1233 * and exactly one copy of the separator is inserted.
1235 * Empty elements are ignored.
1237 * The number of leading copies of the separator on the result is
1238 * the same as the number of leading copies of the separator on
1239 * the first non-empty element.
1241 * The number of trailing copies of the separator on the result is
1242 * the same as the number of trailing copies of the separator on
1243 * the last non-empty element. (Determination of the number of
1244 * trailing copies is done without stripping leading copies, so
1245 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1246 * has 1 trailing copy.)
1248 * However, if there is only a single non-empty element, and there
1249 * are no characters in that element not part of the leading or
1250 * trailing separators, then the result is exactly the original value
1253 * Other than for determination of the number of leading and trailing
1254 * copies of the separator, elements consisting only of copies
1255 * of the separator are ignored.
1257 * Return value: a newly-allocated string that must be freed with g_free().
1260 g_build_path (const gchar *separator,
1261 const gchar *first_element,
1267 g_return_val_if_fail (separator != NULL, NULL);
1269 va_start (args, first_element);
1270 str = g_build_pathv (separator, first_element, args);
1278 * @first_element: the first element in the path
1279 * @Varargs: remaining elements in path, terminated by %NULL
1281 * Creates a filename from a series of elements using the correct
1282 * separator for filenames.
1284 * On Unix, this function behaves identically to <literal>g_build_path
1285 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1287 * On Windows, it takes into account that either the backslash
1288 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1289 * as separator in filenames, but otherwise behaves as on Unix. When
1290 * file pathname separators need to be inserted, the one that last
1291 * previously occurred in the parameters (reading from left to right)
1294 * No attempt is made to force the resulting filename to be an absolute
1295 * path. If the first element is a relative path, the result will
1296 * be a relative path.
1298 * Return value: a newly-allocated string that must be freed with g_free().
1301 g_build_filename (const gchar *first_element,
1308 va_start (args, first_element);
1309 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
1314 /* Code copied from g_build_pathv(), and modifed to use two
1315 * alternative single-character separators.
1319 gboolean is_first = TRUE;
1320 gboolean have_leading = FALSE;
1321 const gchar *single_element = NULL;
1322 const gchar *next_element;
1323 const gchar *last_trailing = NULL;
1324 gchar current_separator = '\\';
1326 va_start (args, first_element);
1328 result = g_string_new (NULL);
1330 next_element = first_element;
1334 const gchar *element;
1340 element = next_element;
1341 next_element = va_arg (args, gchar *);
1346 /* Ignore empty elements */
1355 (*start == '\\' || *start == '/'))
1357 current_separator = *start;
1362 end = start + strlen (start);
1366 while (end >= start + 1 &&
1367 (end[-1] == '\\' || end[-1] == '/'))
1369 current_separator = end[-1];
1373 last_trailing = end;
1374 while (last_trailing >= element + 1 &&
1375 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1380 /* If the leading and trailing separator strings are in the
1381 * same element and overlap, the result is exactly that element
1383 if (last_trailing <= start)
1384 single_element = element;
1386 g_string_append_len (result, element, start - element);
1387 have_leading = TRUE;
1390 single_element = NULL;
1397 g_string_append_len (result, ¤t_separator, 1);
1399 g_string_append_len (result, start, end - start);
1407 g_string_free (result, TRUE);
1408 return g_strdup (single_element);
1413 g_string_append (result, last_trailing);
1415 return g_string_free (result, FALSE);
1422 * @filename: the symbolic link
1423 * @error: return location for a #GError
1425 * Reads the contents of the symbolic link @filename like the POSIX
1426 * readlink() function. The returned string is in the encoding used
1427 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1429 * Returns: A newly allocated string with the contents of the symbolic link,
1430 * or %NULL if an error occurred.
1435 g_file_read_link (const gchar *filename,
1438 #ifdef HAVE_READLINK
1444 buffer = g_malloc (size);
1448 read_size = readlink (filename, buffer, size);
1449 if (read_size < 0) {
1450 gchar *display_filename = g_filename_display_name (filename);
1454 g_file_error_from_errno (errno),
1455 _("Failed to read the symbolic link '%s': %s"),
1457 g_strerror (errno));
1458 g_free (display_filename);
1463 if (read_size < size)
1465 buffer[read_size] = 0;
1470 buffer = g_realloc (buffer, size);
1476 _("Symbolic links not supported"));