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>
43 #endif /* G_OS_WIN32 */
58 * @filename: a filename to test in the GLib file name encoding
59 * @test: bitfield of #GFileTest flags
61 * Returns %TRUE if any of the tests in the bitfield @test are
62 * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS |
63 * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists;
64 * the check whether it's a directory doesn't matter since the existence
65 * test is %TRUE. With the current set of available tests, there's no point
66 * passing in more than one test at a time.
68 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
69 * so for a symbolic link to a regular file g_file_test() will return
70 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
72 * Note, that for a dangling symbolic link g_file_test() will return
73 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
75 * You should never use g_file_test() to test whether it is safe
76 * to perform an operation, because there is always the possibility
77 * of the condition changing before you actually perform the operation.
78 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
79 * to know whether it is is safe to write to a file without being
80 * tricked into writing into a different location. It doesn't work!
82 * <informalexample><programlisting>
83 * /* DON'T DO THIS */
84 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) {
85 * fd = g_open (filename, O_WRONLY);
86 * /* write to fd */
88 * </programlisting></informalexample>
90 * Another thing to note is that %G_FILE_TEST_EXISTS and
91 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
92 * system call. This usually doesn't matter, but if your program
93 * is setuid or setgid it means that these tests will give you
94 * the answer for the real user ID and group ID, rather than the
95 * effective user ID and group ID.
97 * On Windows, there are no symlinks, so testing for
98 * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
99 * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
100 * its name indicates that it is executable, checking for well-known
101 * extensions and those listed in the %PATHEXT environment variable.
103 * Return value: whether a test was %TRUE
106 g_file_test (const gchar *filename,
110 /* stuff missing in std vc6 api */
111 # ifndef INVALID_FILE_ATTRIBUTES
112 # define INVALID_FILE_ATTRIBUTES -1
114 # ifndef FILE_ATTRIBUTE_DEVICE
115 # define FILE_ATTRIBUTE_DEVICE 64
119 if (G_WIN32_HAVE_WIDECHAR_API ())
121 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
123 if (wfilename == NULL)
126 attributes = GetFileAttributesW (wfilename);
132 gchar *cpfilename = g_locale_from_utf8 (filename, -1, NULL, NULL, NULL);
134 if (cpfilename == NULL)
137 attributes = GetFileAttributesA (cpfilename);
142 if (attributes == INVALID_FILE_ATTRIBUTES)
145 if (test & G_FILE_TEST_EXISTS)
148 if (test & G_FILE_TEST_IS_REGULAR)
149 return (attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0;
151 if (test & G_FILE_TEST_IS_DIR)
152 return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
154 if (test & G_FILE_TEST_IS_EXECUTABLE)
156 const gchar *lastdot = strrchr (filename, '.');
157 const gchar *pathext = NULL, *p;
163 if (stricmp (lastdot, ".exe") == 0 ||
164 stricmp (lastdot, ".cmd") == 0 ||
165 stricmp (lastdot, ".bat") == 0 ||
166 stricmp (lastdot, ".com") == 0)
169 /* Check if it is one of the types listed in %PATHEXT% */
171 pathext = g_getenv ("PATHEXT");
175 pathext = g_utf8_casefold (pathext, -1);
177 lastdot = g_utf8_casefold (lastdot, -1);
178 extlen = strlen (lastdot);
183 const gchar *q = strchr (p, ';');
186 if (extlen == q - p &&
187 memcmp (lastdot, p, extlen) == 0)
189 g_free ((gchar *) pathext);
190 g_free ((gchar *) lastdot);
199 g_free ((gchar *) pathext);
200 g_free ((gchar *) lastdot);
206 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
209 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
214 /* For root, on some POSIX systems, access (filename, X_OK)
215 * will succeed even if no executable bits are set on the
216 * file. We fall through to a stat test to avoid that.
220 test &= ~G_FILE_TEST_IS_EXECUTABLE;
222 if (test & G_FILE_TEST_IS_SYMLINK)
226 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
230 if (test & (G_FILE_TEST_IS_REGULAR |
232 G_FILE_TEST_IS_EXECUTABLE))
236 if (stat (filename, &s) == 0)
238 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
241 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
244 /* The extra test for root when access (file, X_OK) succeeds.
246 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
247 ((s.st_mode & S_IXOTH) ||
248 (s.st_mode & S_IXUSR) ||
249 (s.st_mode & S_IXGRP)))
262 /* Binary compatibility version. Not for newly compiled code. */
265 g_file_test (const gchar *filename,
268 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
271 if (utf8_filename == NULL)
274 retval = g_file_test_utf8 (utf8_filename, test);
276 g_free (utf8_filename);
284 g_file_error_quark (void)
288 q = g_quark_from_static_string ("g-file-error-quark");
294 * g_file_error_from_errno:
295 * @err_no: an "errno" value
297 * Gets a #GFileError constant based on the passed-in @errno.
298 * For example, if you pass in %EEXIST this function returns
299 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
300 * assume that all #GFileError values will exist.
302 * Normally a #GFileError value goes into a #GError returned
303 * from a function that manipulates files. So you would use
304 * g_file_error_from_errno() when constructing a #GError.
306 * Return value: #GFileError corresponding to the given @errno
309 g_file_error_from_errno (gint err_no)
315 return G_FILE_ERROR_EXIST;
321 return G_FILE_ERROR_ISDIR;
327 return G_FILE_ERROR_ACCES;
333 return G_FILE_ERROR_NAMETOOLONG;
339 return G_FILE_ERROR_NOENT;
345 return G_FILE_ERROR_NOTDIR;
351 return G_FILE_ERROR_NXIO;
357 return G_FILE_ERROR_NODEV;
363 return G_FILE_ERROR_ROFS;
369 return G_FILE_ERROR_TXTBSY;
375 return G_FILE_ERROR_FAULT;
381 return G_FILE_ERROR_LOOP;
387 return G_FILE_ERROR_NOSPC;
393 return G_FILE_ERROR_NOMEM;
399 return G_FILE_ERROR_MFILE;
405 return G_FILE_ERROR_NFILE;
411 return G_FILE_ERROR_BADF;
417 return G_FILE_ERROR_INVAL;
423 return G_FILE_ERROR_PIPE;
429 return G_FILE_ERROR_AGAIN;
435 return G_FILE_ERROR_INTR;
441 return G_FILE_ERROR_IO;
447 return G_FILE_ERROR_PERM;
453 return G_FILE_ERROR_NOSYS;
458 return G_FILE_ERROR_FAILED;
464 get_contents_stdio (const gchar *display_filename,
474 size_t total_allocated;
476 g_assert (f != NULL);
478 #define STARTING_ALLOC 64
481 total_allocated = STARTING_ALLOC;
482 str = g_malloc (STARTING_ALLOC);
488 bytes = fread (buf, 1, 2048, f);
491 while ((total_bytes + bytes + 1) > total_allocated)
493 total_allocated *= 2;
494 str = g_try_realloc (str, total_allocated);
501 _("Could not allocate %lu bytes to read file \"%s\""),
502 (gulong) total_allocated,
513 g_file_error_from_errno (save_errno),
514 _("Error reading file '%s': %s"),
516 g_strerror (save_errno));
521 memcpy (str + total_bytes, buf, bytes);
522 total_bytes += bytes;
527 str[total_bytes] = '\0';
530 *length = total_bytes;
547 get_contents_regfile (const gchar *display_filename,
548 struct stat *stat_buf,
559 size = stat_buf->st_size;
561 alloc_size = size + 1;
562 buf = g_try_malloc (alloc_size);
569 _("Could not allocate %lu bytes to read file \"%s\""),
577 while (bytes_read < size)
581 rc = read (fd, buf + bytes_read, size - bytes_read);
587 int save_errno = errno;
592 g_file_error_from_errno (save_errno),
593 _("Failed to read from file '%s': %s"),
595 g_strerror (save_errno));
606 buf[bytes_read] = '\0';
609 *length = bytes_read;
625 get_contents_posix (const gchar *filename,
630 struct stat stat_buf;
632 gchar *display_filename = g_filename_display_name (filename);
634 /* O_BINARY useful on Cygwin */
635 fd = open (filename, O_RDONLY|O_BINARY);
639 int save_errno = errno;
643 g_file_error_from_errno (save_errno),
644 _("Failed to open file '%s': %s"),
646 g_strerror (save_errno));
647 g_free (display_filename);
652 /* I don't think this will ever fail, aside from ENOMEM, but. */
653 if (fstat (fd, &stat_buf) < 0)
655 int save_errno = errno;
660 g_file_error_from_errno (save_errno),
661 _("Failed to get attributes of file '%s': fstat() failed: %s"),
663 g_strerror (save_errno));
664 g_free (display_filename);
669 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
671 gboolean retval = get_contents_regfile (display_filename,
677 g_free (display_filename);
686 f = fdopen (fd, "r");
690 int save_errno = errno;
694 g_file_error_from_errno (save_errno),
695 _("Failed to open file '%s': fdopen() failed: %s"),
697 g_strerror (save_errno));
698 g_free (display_filename);
703 retval = get_contents_stdio (display_filename, f, contents, length, error);
704 g_free (display_filename);
710 #else /* G_OS_WIN32 */
713 get_contents_win32 (const gchar *filename,
720 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
721 gchar *display_filename = g_filename_display_name (filename);
724 f = _wfopen (wfilename, L"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);
817 * mkstemp() implementation is from the GNU C library.
818 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
822 * @tmpl: template filename
824 * Opens a temporary file. See the mkstemp() documentation
825 * on most UNIX-like systems. This is a portability wrapper, which simply calls
826 * mkstemp() on systems that have it, and implements
827 * it in GLib otherwise.
829 * The parameter is a string that should match the rules for
830 * mkstemp(), i.e. end in "XXXXXX". The X string will
831 * be modified to form the name of a file that didn't exist.
832 * The string should be in the GLib file name encoding. Most importantly,
833 * on Windows it should be in UTF-8.
835 * Return value: A file handle (as from open()) to the file
836 * opened for reading and writing. The file is opened in binary mode
837 * on platforms where there is a difference. The file handle should be
838 * closed with close(). In case of errors, -1 is returned.
841 g_mkstemp (gchar *tmpl)
844 return mkstemp (tmpl);
849 static const char letters[] =
850 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
851 static const int NLETTERS = sizeof (letters) - 1;
854 static int counter = 0;
857 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
863 /* This is where the Xs start. */
864 XXXXXX = &tmpl[len - 6];
866 /* Get some more or less random data. */
867 g_get_current_time (&tv);
868 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
870 for (count = 0; count < 100; value += 7777, ++count)
874 /* Fill in the random bits. */
875 XXXXXX[0] = letters[v % NLETTERS];
877 XXXXXX[1] = letters[v % NLETTERS];
879 XXXXXX[2] = letters[v % NLETTERS];
881 XXXXXX[3] = letters[v % NLETTERS];
883 XXXXXX[4] = letters[v % NLETTERS];
885 XXXXXX[5] = letters[v % NLETTERS];
887 /* tmpl is in UTF-8 on Windows, thus use g_open() */
888 fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
892 else if (errno != EEXIST)
893 /* Any other error will apply also to other names we might
894 * try, and there are 2^32 or so of them, so give up now.
899 /* We got out of the loop because we ran out of combinations to try. */
909 /* Binary compatibility version. Not for newly compiled code. */
912 g_mkstemp (gchar *tmpl)
917 static const char letters[] =
918 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
919 static const int NLETTERS = sizeof (letters) - 1;
922 static int counter = 0;
925 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
931 /* This is where the Xs start. */
932 XXXXXX = &tmpl[len - 6];
934 /* Get some more or less random data. */
935 g_get_current_time (&tv);
936 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
938 for (count = 0; count < 100; value += 7777, ++count)
942 /* Fill in the random bits. */
943 XXXXXX[0] = letters[v % NLETTERS];
945 XXXXXX[1] = letters[v % NLETTERS];
947 XXXXXX[2] = letters[v % NLETTERS];
949 XXXXXX[3] = letters[v % NLETTERS];
951 XXXXXX[4] = letters[v % NLETTERS];
953 XXXXXX[5] = letters[v % NLETTERS];
955 /* This is the backward compatibility system codepage version,
956 * thus use normal open().
958 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
962 else if (errno != EEXIST)
963 /* Any other error will apply also to other names we might
964 * try, and there are 2^32 or so of them, so give up now.
969 /* We got out of the loop because we ran out of combinations to try. */
978 * @tmpl: Template for file name, as in g_mkstemp(), basename only
979 * @name_used: location to store actual name used
980 * @error: return location for a #GError
982 * Opens a file for writing in the preferred directory for temporary
983 * files (as returned by g_get_tmp_dir()).
985 * @tmpl should be a string in the GLib file name encoding ending with
986 * six 'X' characters, as the parameter to g_mkstemp() (or mkstemp()).
987 * However, unlike these functions, the template should only be a
988 * basename, no directory components are allowed. If template is
989 * %NULL, a default template is used.
991 * Note that in contrast to g_mkstemp() (and mkstemp())
992 * @tmpl is not modified, and might thus be a read-only literal string.
994 * The actual name used is returned in @name_used if non-%NULL. This
995 * string should be freed with g_free() when not needed any longer.
996 * The returned name is in the GLib file name encoding.
998 * Return value: A file handle (as from open()) to
999 * the file opened for reading and writing. The file is opened in binary
1000 * mode on platforms where there is a difference. The file handle should be
1001 * closed with close(). In case of errors, -1 is returned
1002 * and @error will be set.
1005 g_file_open_tmp (const gchar *tmpl,
1018 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1020 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1024 gchar *display_tmpl = g_filename_display_name (tmpl);
1031 G_FILE_ERROR_FAILED,
1032 _("Template '%s' invalid, should not contain a '%s'"),
1034 g_free (display_tmpl);
1039 if (strlen (tmpl) < 6 ||
1040 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
1042 gchar *display_tmpl = g_filename_display_name (tmpl);
1045 G_FILE_ERROR_FAILED,
1046 _("Template '%s' doesn't end with XXXXXX"),
1048 g_free (display_tmpl);
1052 tmpdir = g_get_tmp_dir ();
1054 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1057 sep = G_DIR_SEPARATOR_S;
1059 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1061 retval = g_mkstemp (fulltemplate);
1065 int save_errno = errno;
1066 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1070 g_file_error_from_errno (save_errno),
1071 _("Failed to create file '%s': %s"),
1072 display_fulltemplate, g_strerror (save_errno));
1073 g_free (display_fulltemplate);
1074 g_free (fulltemplate);
1079 *name_used = fulltemplate;
1081 g_free (fulltemplate);
1088 #undef g_file_open_tmp
1090 /* Binary compatibility version. Not for newly compiled code. */
1093 g_file_open_tmp (const gchar *tmpl,
1097 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1098 gchar *utf8_name_used;
1101 if (utf8_tmpl == NULL)
1104 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1110 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1112 g_free (utf8_name_used);
1120 g_build_pathv (const gchar *separator,
1121 const gchar *first_element,
1125 gint separator_len = strlen (separator);
1126 gboolean is_first = TRUE;
1127 gboolean have_leading = FALSE;
1128 const gchar *single_element = NULL;
1129 const gchar *next_element;
1130 const gchar *last_trailing = NULL;
1132 result = g_string_new (NULL);
1134 next_element = first_element;
1138 const gchar *element;
1144 element = next_element;
1145 next_element = va_arg (args, gchar *);
1150 /* Ignore empty elements */
1159 strncmp (start, separator, separator_len) == 0)
1160 start += separator_len;
1163 end = start + strlen (start);
1167 while (end >= start + separator_len &&
1168 strncmp (end - separator_len, separator, separator_len) == 0)
1169 end -= separator_len;
1171 last_trailing = end;
1172 while (last_trailing >= element + separator_len &&
1173 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1174 last_trailing -= separator_len;
1178 /* If the leading and trailing separator strings are in the
1179 * same element and overlap, the result is exactly that element
1181 if (last_trailing <= start)
1182 single_element = element;
1184 g_string_append_len (result, element, start - element);
1185 have_leading = TRUE;
1188 single_element = NULL;
1195 g_string_append (result, separator);
1197 g_string_append_len (result, start, end - start);
1203 g_string_free (result, TRUE);
1204 return g_strdup (single_element);
1209 g_string_append (result, last_trailing);
1211 return g_string_free (result, FALSE);
1217 * @separator: a string used to separator the elements of the path.
1218 * @first_element: the first element in the path
1219 * @Varargs: remaining elements in path, terminated by %NULL
1221 * Creates a path from a series of elements using @separator as the
1222 * separator between elements. At the boundary between two elements,
1223 * any trailing occurrences of separator in the first element, or
1224 * leading occurrences of separator in the second element are removed
1225 * and exactly one copy of the separator is inserted.
1227 * Empty elements are ignored.
1229 * The number of leading copies of the separator on the result is
1230 * the same as the number of leading copies of the separator on
1231 * the first non-empty element.
1233 * The number of trailing copies of the separator on the result is
1234 * the same as the number of trailing copies of the separator on
1235 * the last non-empty element. (Determination of the number of
1236 * trailing copies is done without stripping leading copies, so
1237 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1238 * has 1 trailing copy.)
1240 * However, if there is only a single non-empty element, and there
1241 * are no characters in that element not part of the leading or
1242 * trailing separators, then the result is exactly the original value
1245 * Other than for determination of the number of leading and trailing
1246 * copies of the separator, elements consisting only of copies
1247 * of the separator are ignored.
1249 * Return value: a newly-allocated string that must be freed with g_free().
1252 g_build_path (const gchar *separator,
1253 const gchar *first_element,
1259 g_return_val_if_fail (separator != NULL, NULL);
1261 va_start (args, first_element);
1262 str = g_build_pathv (separator, first_element, args);
1270 * @first_element: the first element in the path
1271 * @Varargs: remaining elements in path, terminated by %NULL
1273 * Creates a filename from a series of elements using the correct
1274 * separator for filenames.
1276 * On Unix, this function behaves identically to <literal>g_build_path
1277 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1279 * On Windows, it takes into account that either the backslash
1280 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1281 * as separator in filenames, but otherwise behaves as on Unix. When
1282 * file pathname separators need to be inserted, the one that last
1283 * previously occurred in the parameters (reading from left to right)
1286 * No attempt is made to force the resulting filename to be an absolute
1287 * path. If the first element is a relative path, the result will
1288 * be a relative path.
1290 * Return value: a newly-allocated string that must be freed with g_free().
1293 g_build_filename (const gchar *first_element,
1300 va_start (args, first_element);
1301 str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
1306 /* Code copied from g_build_pathv(), and modifed to use two
1307 * alternative single-character separators.
1311 gboolean is_first = TRUE;
1312 gboolean have_leading = FALSE;
1313 const gchar *single_element = NULL;
1314 const gchar *next_element;
1315 const gchar *last_trailing = NULL;
1316 gchar current_separator = '\\';
1318 va_start (args, first_element);
1320 result = g_string_new (NULL);
1322 next_element = first_element;
1326 const gchar *element;
1332 element = next_element;
1333 next_element = va_arg (args, gchar *);
1338 /* Ignore empty elements */
1347 (*start == '\\' || *start == '/'))
1349 current_separator = *start;
1354 end = start + strlen (start);
1358 while (end >= start + 1 &&
1359 (end[-1] == '\\' || end[-1] == '/'))
1361 current_separator = end[-1];
1365 last_trailing = end;
1366 while (last_trailing >= element + 1 &&
1367 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1372 /* If the leading and trailing separator strings are in the
1373 * same element and overlap, the result is exactly that element
1375 if (last_trailing <= start)
1376 single_element = element;
1378 g_string_append_len (result, element, start - element);
1379 have_leading = TRUE;
1382 single_element = NULL;
1389 g_string_append_len (result, ¤t_separator, 1);
1391 g_string_append_len (result, start, end - start);
1399 g_string_free (result, TRUE);
1400 return g_strdup (single_element);
1405 g_string_append (result, last_trailing);
1407 return g_string_free (result, FALSE);
1414 * @filename: the symbolic link
1415 * @error: return location for a #GError
1417 * Reads the contents of the symbolic link @filename like the POSIX
1418 * readlink() function. The returned string is in the encoding used
1419 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1421 * Returns: A newly allocated string with the contents of the symbolic link,
1422 * or %NULL if an error occurred.
1427 g_file_read_link (const gchar *filename,
1430 #ifdef HAVE_READLINK
1436 buffer = g_malloc (size);
1440 read_size = readlink (filename, buffer, size);
1441 if (read_size < 0) {
1442 int save_errno = errno;
1443 gchar *display_filename = g_filename_display_name (filename);
1448 g_file_error_from_errno (save_errno),
1449 _("Failed to read the symbolic link '%s': %s"),
1451 g_strerror (save_errno));
1452 g_free (display_filename);
1457 if (read_size < size)
1459 buffer[read_size] = 0;
1464 buffer = g_realloc (buffer, size);
1470 _("Symbolic links not supported"));