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 */
57 static gint create_temp_file (gchar *tmpl,
61 * g_mkdir_with_parents:
62 * @pathname: a pathname in the GLib file name encoding
63 * @mode: permissions to use for newly created directories
65 * Create a directory if it doesn't already exist. Create intermediate
66 * parent directories as needed, too.
68 * Returns: 0 if the directory already exists, or was successfully
69 * created. Returns -1 if an error occurred, with errno set.
74 g_mkdir_with_parents (const gchar *pathname,
79 if (pathname == NULL || *pathname == '\0')
85 fn = g_strdup (pathname);
87 if (g_path_is_absolute (fn))
88 p = (gchar *) g_path_skip_root (fn);
94 while (*p && !G_IS_DIR_SEPARATOR (*p))
102 if (!g_file_test (fn, G_FILE_TEST_EXISTS))
104 if (g_mkdir (fn, mode) == -1)
106 int errno_save = errno;
112 else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
120 *p++ = G_DIR_SEPARATOR;
121 while (*p && G_IS_DIR_SEPARATOR (*p))
134 * @filename: a filename to test in the GLib file name encoding
135 * @test: bitfield of #GFileTest flags
137 * Returns %TRUE if any of the tests in the bitfield @test are
138 * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS |
139 * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists;
140 * the check whether it's a directory doesn't matter since the existence
141 * test is %TRUE. With the current set of available tests, there's no point
142 * passing in more than one test at a time.
144 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
145 * so for a symbolic link to a regular file g_file_test() will return
146 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
148 * Note, that for a dangling symbolic link g_file_test() will return
149 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
151 * You should never use g_file_test() to test whether it is safe
152 * to perform an operation, because there is always the possibility
153 * of the condition changing before you actually perform the operation.
154 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
155 * to know whether it is is safe to write to a file without being
156 * tricked into writing into a different location. It doesn't work!
158 * <informalexample><programlisting>
159 * /* DON'T DO THIS */
160 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) {
161 * fd = g_open (filename, O_WRONLY);
162 * /* write to fd */
164 * </programlisting></informalexample>
166 * Another thing to note is that %G_FILE_TEST_EXISTS and
167 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
168 * system call. This usually doesn't matter, but if your program
169 * is setuid or setgid it means that these tests will give you
170 * the answer for the real user ID and group ID, rather than the
171 * effective user ID and group ID.
173 * On Windows, there are no symlinks, so testing for
174 * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
175 * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
176 * its name indicates that it is executable, checking for well-known
177 * extensions and those listed in the %PATHEXT environment variable.
179 * Return value: whether a test was %TRUE
182 g_file_test (const gchar *filename,
186 /* stuff missing in std vc6 api */
187 # ifndef INVALID_FILE_ATTRIBUTES
188 # define INVALID_FILE_ATTRIBUTES -1
190 # ifndef FILE_ATTRIBUTE_DEVICE
191 # define FILE_ATTRIBUTE_DEVICE 64
195 if (G_WIN32_HAVE_WIDECHAR_API ())
197 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
199 if (wfilename == NULL)
202 attributes = GetFileAttributesW (wfilename);
208 gchar *cpfilename = g_locale_from_utf8 (filename, -1, NULL, NULL, NULL);
210 if (cpfilename == NULL)
213 attributes = GetFileAttributesA (cpfilename);
218 if (attributes == INVALID_FILE_ATTRIBUTES)
221 if (test & G_FILE_TEST_EXISTS)
224 if (test & G_FILE_TEST_IS_REGULAR)
225 return (attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0;
227 if (test & G_FILE_TEST_IS_DIR)
228 return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
230 if (test & G_FILE_TEST_IS_EXECUTABLE)
232 const gchar *lastdot = strrchr (filename, '.');
233 const gchar *pathext = NULL, *p;
239 if (stricmp (lastdot, ".exe") == 0 ||
240 stricmp (lastdot, ".cmd") == 0 ||
241 stricmp (lastdot, ".bat") == 0 ||
242 stricmp (lastdot, ".com") == 0)
245 /* Check if it is one of the types listed in %PATHEXT% */
247 pathext = g_getenv ("PATHEXT");
251 pathext = g_utf8_casefold (pathext, -1);
253 lastdot = g_utf8_casefold (lastdot, -1);
254 extlen = strlen (lastdot);
259 const gchar *q = strchr (p, ';');
262 if (extlen == q - p &&
263 memcmp (lastdot, p, extlen) == 0)
265 g_free ((gchar *) pathext);
266 g_free ((gchar *) lastdot);
275 g_free ((gchar *) pathext);
276 g_free ((gchar *) lastdot);
282 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
285 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
290 /* For root, on some POSIX systems, access (filename, X_OK)
291 * will succeed even if no executable bits are set on the
292 * file. We fall through to a stat test to avoid that.
296 test &= ~G_FILE_TEST_IS_EXECUTABLE;
298 if (test & G_FILE_TEST_IS_SYMLINK)
302 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
306 if (test & (G_FILE_TEST_IS_REGULAR |
308 G_FILE_TEST_IS_EXECUTABLE))
312 if (stat (filename, &s) == 0)
314 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
317 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
320 /* The extra test for root when access (file, X_OK) succeeds.
322 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
323 ((s.st_mode & S_IXOTH) ||
324 (s.st_mode & S_IXUSR) ||
325 (s.st_mode & S_IXGRP)))
338 /* Binary compatibility version. Not for newly compiled code. */
341 g_file_test (const gchar *filename,
344 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
347 if (utf8_filename == NULL)
350 retval = g_file_test_utf8 (utf8_filename, test);
352 g_free (utf8_filename);
360 g_file_error_quark (void)
364 q = g_quark_from_static_string ("g-file-error-quark");
370 * g_file_error_from_errno:
371 * @err_no: an "errno" value
373 * Gets a #GFileError constant based on the passed-in @errno.
374 * For example, if you pass in %EEXIST this function returns
375 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
376 * assume that all #GFileError values will exist.
378 * Normally a #GFileError value goes into a #GError returned
379 * from a function that manipulates files. So you would use
380 * g_file_error_from_errno() when constructing a #GError.
382 * Return value: #GFileError corresponding to the given @errno
385 g_file_error_from_errno (gint err_no)
391 return G_FILE_ERROR_EXIST;
397 return G_FILE_ERROR_ISDIR;
403 return G_FILE_ERROR_ACCES;
409 return G_FILE_ERROR_NAMETOOLONG;
415 return G_FILE_ERROR_NOENT;
421 return G_FILE_ERROR_NOTDIR;
427 return G_FILE_ERROR_NXIO;
433 return G_FILE_ERROR_NODEV;
439 return G_FILE_ERROR_ROFS;
445 return G_FILE_ERROR_TXTBSY;
451 return G_FILE_ERROR_FAULT;
457 return G_FILE_ERROR_LOOP;
463 return G_FILE_ERROR_NOSPC;
469 return G_FILE_ERROR_NOMEM;
475 return G_FILE_ERROR_MFILE;
481 return G_FILE_ERROR_NFILE;
487 return G_FILE_ERROR_BADF;
493 return G_FILE_ERROR_INVAL;
499 return G_FILE_ERROR_PIPE;
505 return G_FILE_ERROR_AGAIN;
511 return G_FILE_ERROR_INTR;
517 return G_FILE_ERROR_IO;
523 return G_FILE_ERROR_PERM;
529 return G_FILE_ERROR_NOSYS;
534 return G_FILE_ERROR_FAILED;
540 get_contents_stdio (const gchar *display_filename,
549 size_t total_bytes = 0;
550 size_t total_allocated = 0;
553 g_assert (f != NULL);
559 bytes = fread (buf, 1, sizeof (buf), f);
562 while ((total_bytes + bytes + 1) > total_allocated)
565 total_allocated *= 2;
567 total_allocated = MIN (bytes + 1, sizeof (buf));
569 tmp = g_try_realloc (str, total_allocated);
576 _("Could not allocate %lu bytes to read file \"%s\""),
577 (gulong) total_allocated,
590 g_file_error_from_errno (save_errno),
591 _("Error reading file '%s': %s"),
593 g_strerror (save_errno));
598 memcpy (str + total_bytes, buf, bytes);
599 total_bytes += bytes;
604 if (total_allocated == 0)
605 str = g_new (gchar, 1);
607 str[total_bytes] = '\0';
610 *length = total_bytes;
627 get_contents_regfile (const gchar *display_filename,
628 struct stat *stat_buf,
639 size = stat_buf->st_size;
641 alloc_size = size + 1;
642 buf = g_try_malloc (alloc_size);
649 _("Could not allocate %lu bytes to read file \"%s\""),
657 while (bytes_read < size)
661 rc = read (fd, buf + bytes_read, size - bytes_read);
667 int save_errno = errno;
672 g_file_error_from_errno (save_errno),
673 _("Failed to read from file '%s': %s"),
675 g_strerror (save_errno));
686 buf[bytes_read] = '\0';
689 *length = bytes_read;
705 get_contents_posix (const gchar *filename,
710 struct stat stat_buf;
712 gchar *display_filename = g_filename_display_name (filename);
714 /* O_BINARY useful on Cygwin */
715 fd = open (filename, O_RDONLY|O_BINARY);
719 int save_errno = errno;
723 g_file_error_from_errno (save_errno),
724 _("Failed to open file '%s': %s"),
726 g_strerror (save_errno));
727 g_free (display_filename);
732 /* I don't think this will ever fail, aside from ENOMEM, but. */
733 if (fstat (fd, &stat_buf) < 0)
735 int save_errno = errno;
740 g_file_error_from_errno (save_errno),
741 _("Failed to get attributes of file '%s': fstat() failed: %s"),
743 g_strerror (save_errno));
744 g_free (display_filename);
749 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
751 gboolean retval = get_contents_regfile (display_filename,
757 g_free (display_filename);
766 f = fdopen (fd, "r");
770 int save_errno = errno;
774 g_file_error_from_errno (save_errno),
775 _("Failed to open file '%s': fdopen() failed: %s"),
777 g_strerror (save_errno));
778 g_free (display_filename);
783 retval = get_contents_stdio (display_filename, f, contents, length, error);
784 g_free (display_filename);
790 #else /* G_OS_WIN32 */
793 get_contents_win32 (const gchar *filename,
800 gchar *display_filename = g_filename_display_name (filename);
803 f = g_fopen (filename, "rb");
810 g_file_error_from_errno (save_errno),
811 _("Failed to open file '%s': %s"),
813 g_strerror (save_errno));
814 g_free (display_filename);
819 retval = get_contents_stdio (display_filename, f, contents, length, error);
820 g_free (display_filename);
828 * g_file_get_contents:
829 * @filename: name of a file to read contents from, in the GLib file name encoding
830 * @contents: location to store an allocated string
831 * @length: location to store length in bytes of the contents, or %NULL
832 * @error: return location for a #GError, or %NULL
834 * Reads an entire file into allocated memory, with good error
837 * If the call was successful, it returns %TRUE and sets @contents to the file
838 * contents and @length to the length of the file contents in bytes. The string
839 * stored in @contents will be nul-terminated, so for text files you can pass
840 * %NULL for the @length argument. If the call was not successful, it returns
841 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
842 * codes are those in the #GFileError enumeration. In the error case,
843 * @contents is set to %NULL and @length is set to zero.
845 * Return value: %TRUE on success, %FALSE if an error occurred
848 g_file_get_contents (const gchar *filename,
853 g_return_val_if_fail (filename != NULL, FALSE);
854 g_return_val_if_fail (contents != NULL, FALSE);
861 return get_contents_win32 (filename, contents, length, error);
863 return get_contents_posix (filename, contents, length, error);
869 #undef g_file_get_contents
871 /* Binary compatibility version. Not for newly compiled code. */
874 g_file_get_contents (const gchar *filename,
879 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
882 if (utf8_filename == NULL)
885 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
887 g_free (utf8_filename);
895 rename_file (const char *old_name,
896 const char *new_name,
900 if (g_rename (old_name, new_name) == -1)
902 int save_errno = errno;
903 gchar *display_old_name = g_filename_display_name (old_name);
904 gchar *display_new_name = g_filename_display_name (new_name);
908 g_file_error_from_errno (save_errno),
909 _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
912 g_strerror (save_errno));
914 g_free (display_old_name);
915 g_free (display_new_name);
924 write_to_temp_file (const gchar *contents,
926 const gchar *template,
938 tmp_name = g_strdup_printf ("%s.XXXXXX", template);
941 fd = create_temp_file (tmp_name, 0666);
942 display_name = g_filename_display_name (tmp_name);
949 g_file_error_from_errno (save_errno),
950 _("Failed to create file '%s': %s"),
951 display_name, g_strerror (save_errno));
957 file = fdopen (fd, "wb");
963 g_file_error_from_errno (save_errno),
964 _("Failed to open file '%s' for writing: fdopen() failed: %s"),
966 g_strerror (save_errno));
980 n_written = fwrite (contents, 1, length, file);
982 if (n_written < length)
988 g_file_error_from_errno (save_errno),
989 _("Failed to write file '%s': fwrite() failed: %s"),
991 g_strerror (save_errno));
1001 if (fclose (file) == EOF)
1007 g_file_error_from_errno (save_errno),
1008 _("Failed to close file '%s': fclose() failed: %s"),
1010 g_strerror (save_errno));
1012 g_unlink (tmp_name);
1017 retval = g_strdup (tmp_name);
1021 g_free (display_name);
1027 * g_file_set_contents:
1028 * @filename: name of a file to write @contents to, in the GLib file name
1030 * @contents: string to write to the file
1031 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1032 * @error: return location for a #GError, or %NULL
1034 * Writes all of @contents to a file named @filename, with good error checking.
1035 * If a file called @filename already exists it will be overwritten.
1037 * This write is atomic in the sense that it is first written to a temporary
1038 * file which is then renamed to the final name. Notes:
1041 * On Unix, if @filename already exists hard links to @filename will break.
1042 * Also since the file is recreated, existing permissions, access control
1043 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1044 * the link itself will be replaced, not the linked file.
1047 * On Windows renaming a file will not remove an existing file with the
1048 * new name, so on Windows there is a race condition between the existing
1049 * file being removed and the temporary file being renamed.
1052 * On Windows there is no way to remove a file that is open to some
1053 * process, or mapped into memory. Thus, this function will fail if
1054 * @filename already exists and is open.
1058 * If the call was sucessful, it returns %TRUE. If the call was not successful,
1059 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1060 * Possible error codes are those in the #GFileError enumeration.
1062 * Return value: %TRUE on success, %FALSE if an error occurred
1067 g_file_set_contents (const gchar *filename,
1068 const gchar *contents,
1072 gchar *tmp_filename;
1074 GError *rename_error = NULL;
1076 g_return_val_if_fail (filename != NULL, FALSE);
1077 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1078 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1079 g_return_val_if_fail (length >= -1, FALSE);
1082 length = strlen (contents);
1084 tmp_filename = write_to_temp_file (contents, length, filename, error);
1092 if (!rename_file (tmp_filename, filename, &rename_error))
1096 g_unlink (tmp_filename);
1097 g_propagate_error (error, rename_error);
1101 #else /* G_OS_WIN32 */
1103 /* Renaming failed, but on Windows this may just mean
1104 * the file already exists. So if the target file
1105 * exists, try deleting it and do the rename again.
1107 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1109 g_unlink (tmp_filename);
1110 g_propagate_error (error, rename_error);
1115 g_error_free (rename_error);
1117 if (g_unlink (filename) == -1)
1119 gchar *display_filename = g_filename_display_name (filename);
1121 int save_errno = errno;
1125 g_file_error_from_errno (save_errno),
1126 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1128 g_strerror (save_errno));
1130 g_free (display_filename);
1131 g_unlink (tmp_filename);
1136 if (!rename_file (tmp_filename, filename, error))
1138 g_unlink (tmp_filename);
1149 g_free (tmp_filename);
1154 * create_temp_file based on the mkstemp implementation from the GNU C library.
1155 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1158 create_temp_file (gchar *tmpl,
1164 static const char letters[] =
1165 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1166 static const int NLETTERS = sizeof (letters) - 1;
1169 static int counter = 0;
1171 len = strlen (tmpl);
1172 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
1178 /* This is where the Xs start. */
1179 XXXXXX = &tmpl[len - 6];
1181 /* Get some more or less random data. */
1182 g_get_current_time (&tv);
1183 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1185 for (count = 0; count < 100; value += 7777, ++count)
1189 /* Fill in the random bits. */
1190 XXXXXX[0] = letters[v % NLETTERS];
1192 XXXXXX[1] = letters[v % NLETTERS];
1194 XXXXXX[2] = letters[v % NLETTERS];
1196 XXXXXX[3] = letters[v % NLETTERS];
1198 XXXXXX[4] = letters[v % NLETTERS];
1200 XXXXXX[5] = letters[v % NLETTERS];
1202 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1203 fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, permissions);
1207 else if (errno != EEXIST)
1208 /* Any other error will apply also to other names we might
1209 * try, and there are 2^32 or so of them, so give up now.
1214 /* We got out of the loop because we ran out of combinations to try. */
1221 * @tmpl: template filename
1223 * Opens a temporary file. See the mkstemp() documentation
1224 * on most UNIX-like systems. This is a portability wrapper, which simply calls
1225 * mkstemp() on systems that have it, and implements
1226 * it in GLib otherwise.
1228 * The parameter is a string that should match the rules for
1229 * mkstemp(), i.e. end in "XXXXXX". The X string will
1230 * be modified to form the name of a file that didn't exist.
1231 * The string should be in the GLib file name encoding. Most importantly,
1232 * on Windows it should be in UTF-8.
1234 * Return value: A file handle (as from open()) to the file
1235 * opened for reading and writing. The file is opened in binary mode
1236 * on platforms where there is a difference. The file handle should be
1237 * closed with close(). In case of errors, -1 is returned.
1240 g_mkstemp (gchar *tmpl)
1243 return mkstemp (tmpl);
1245 return create_temp_file (tmpl, 0600);
1253 /* Binary compatibility version. Not for newly compiled code. */
1256 g_mkstemp (gchar *tmpl)
1261 static const char letters[] =
1262 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1263 static const int NLETTERS = sizeof (letters) - 1;
1266 static int counter = 0;
1268 len = strlen (tmpl);
1269 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
1275 /* This is where the Xs start. */
1276 XXXXXX = &tmpl[len - 6];
1278 /* Get some more or less random data. */
1279 g_get_current_time (&tv);
1280 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1282 for (count = 0; count < 100; value += 7777, ++count)
1286 /* Fill in the random bits. */
1287 XXXXXX[0] = letters[v % NLETTERS];
1289 XXXXXX[1] = letters[v % NLETTERS];
1291 XXXXXX[2] = letters[v % NLETTERS];
1293 XXXXXX[3] = letters[v % NLETTERS];
1295 XXXXXX[4] = letters[v % NLETTERS];
1297 XXXXXX[5] = letters[v % NLETTERS];
1299 /* This is the backward compatibility system codepage version,
1300 * thus use normal open().
1302 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1306 else if (errno != EEXIST)
1307 /* Any other error will apply also to other names we might
1308 * try, and there are 2^32 or so of them, so give up now.
1313 /* We got out of the loop because we ran out of combinations to try. */
1322 * @tmpl: Template for file name, as in g_mkstemp(), basename only
1323 * @name_used: location to store actual name used
1324 * @error: return location for a #GError
1326 * Opens a file for writing in the preferred directory for temporary
1327 * files (as returned by g_get_tmp_dir()).
1329 * @tmpl should be a string in the GLib file name encoding ending with
1330 * six 'X' characters, as the parameter to g_mkstemp() (or mkstemp()).
1331 * However, unlike these functions, the template should only be a
1332 * basename, no directory components are allowed. If template is
1333 * %NULL, a default template is used.
1335 * Note that in contrast to g_mkstemp() (and mkstemp())
1336 * @tmpl is not modified, and might thus be a read-only literal string.
1338 * The actual name used is returned in @name_used if non-%NULL. This
1339 * string should be freed with g_free() when not needed any longer.
1340 * The returned name is in the GLib file name encoding.
1342 * Return value: A file handle (as from open()) to
1343 * the file opened for reading and writing. The file is opened in binary
1344 * mode on platforms where there is a difference. The file handle should be
1345 * closed with close(). In case of errors, -1 is returned
1346 * and @error will be set.
1349 g_file_open_tmp (const gchar *tmpl,
1362 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1364 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1368 gchar *display_tmpl = g_filename_display_name (tmpl);
1375 G_FILE_ERROR_FAILED,
1376 _("Template '%s' invalid, should not contain a '%s'"),
1378 g_free (display_tmpl);
1383 if (strlen (tmpl) < 6 ||
1384 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
1386 gchar *display_tmpl = g_filename_display_name (tmpl);
1389 G_FILE_ERROR_FAILED,
1390 _("Template '%s' doesn't end with XXXXXX"),
1392 g_free (display_tmpl);
1396 tmpdir = g_get_tmp_dir ();
1398 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1401 sep = G_DIR_SEPARATOR_S;
1403 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1405 retval = g_mkstemp (fulltemplate);
1409 int save_errno = errno;
1410 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1414 g_file_error_from_errno (save_errno),
1415 _("Failed to create file '%s': %s"),
1416 display_fulltemplate, g_strerror (save_errno));
1417 g_free (display_fulltemplate);
1418 g_free (fulltemplate);
1423 *name_used = fulltemplate;
1425 g_free (fulltemplate);
1432 #undef g_file_open_tmp
1434 /* Binary compatibility version. Not for newly compiled code. */
1437 g_file_open_tmp (const gchar *tmpl,
1441 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1442 gchar *utf8_name_used;
1445 if (utf8_tmpl == NULL)
1448 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1454 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1456 g_free (utf8_name_used);
1464 g_build_path_va (const gchar *separator,
1465 const gchar *first_element,
1470 gint separator_len = strlen (separator);
1471 gboolean is_first = TRUE;
1472 gboolean have_leading = FALSE;
1473 const gchar *single_element = NULL;
1474 const gchar *next_element;
1475 const gchar *last_trailing = NULL;
1478 result = g_string_new (NULL);
1481 next_element = str_array[i++];
1483 next_element = first_element;
1487 const gchar *element;
1493 element = next_element;
1495 next_element = str_array[i++];
1497 next_element = va_arg (*args, gchar *);
1502 /* Ignore empty elements */
1511 strncmp (start, separator, separator_len) == 0)
1512 start += separator_len;
1515 end = start + strlen (start);
1519 while (end >= start + separator_len &&
1520 strncmp (end - separator_len, separator, separator_len) == 0)
1521 end -= separator_len;
1523 last_trailing = end;
1524 while (last_trailing >= element + separator_len &&
1525 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1526 last_trailing -= separator_len;
1530 /* If the leading and trailing separator strings are in the
1531 * same element and overlap, the result is exactly that element
1533 if (last_trailing <= start)
1534 single_element = element;
1536 g_string_append_len (result, element, start - element);
1537 have_leading = TRUE;
1540 single_element = NULL;
1547 g_string_append (result, separator);
1549 g_string_append_len (result, start, end - start);
1555 g_string_free (result, TRUE);
1556 return g_strdup (single_element);
1561 g_string_append (result, last_trailing);
1563 return g_string_free (result, FALSE);
1569 * @separator: a string used to separator the elements of the path.
1570 * @args: %NULL-terminated array of strings containing the path elements.
1572 * Behaves exactly like g_build_path(), but takes the path elements
1573 * as a string array, instead of varargs. This function is mainly
1574 * meant for language bindings.
1576 * Return value: a newly-allocated string that must be freed with g_free().
1581 g_build_pathv (const gchar *separator,
1587 return g_build_path_va (separator, NULL, NULL, args);
1593 * @separator: a string used to separator the elements of the path.
1594 * @first_element: the first element in the path
1595 * @Varargs: remaining elements in path, terminated by %NULL
1597 * Creates a path from a series of elements using @separator as the
1598 * separator between elements. At the boundary between two elements,
1599 * any trailing occurrences of separator in the first element, or
1600 * leading occurrences of separator in the second element are removed
1601 * and exactly one copy of the separator is inserted.
1603 * Empty elements are ignored.
1605 * The number of leading copies of the separator on the result is
1606 * the same as the number of leading copies of the separator on
1607 * the first non-empty element.
1609 * The number of trailing copies of the separator on the result is
1610 * the same as the number of trailing copies of the separator on
1611 * the last non-empty element. (Determination of the number of
1612 * trailing copies is done without stripping leading copies, so
1613 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1614 * has 1 trailing copy.)
1616 * However, if there is only a single non-empty element, and there
1617 * are no characters in that element not part of the leading or
1618 * trailing separators, then the result is exactly the original value
1621 * Other than for determination of the number of leading and trailing
1622 * copies of the separator, elements consisting only of copies
1623 * of the separator are ignored.
1625 * Return value: a newly-allocated string that must be freed with g_free().
1628 g_build_path (const gchar *separator,
1629 const gchar *first_element,
1635 g_return_val_if_fail (separator != NULL, NULL);
1637 va_start (args, first_element);
1638 str = g_build_path_va (separator, first_element, &args, NULL);
1647 g_build_pathname_va (const gchar *first_element,
1651 /* Code copied from g_build_pathv(), and modified to use two
1652 * alternative single-character separators.
1655 gboolean is_first = TRUE;
1656 gboolean have_leading = FALSE;
1657 const gchar *single_element = NULL;
1658 const gchar *next_element;
1659 const gchar *last_trailing = NULL;
1660 gchar current_separator = '\\';
1663 result = g_string_new (NULL);
1666 next_element = str_array[i++];
1668 next_element = first_element;
1672 const gchar *element;
1678 element = next_element;
1680 next_element = str_array[i++];
1682 next_element = va_arg (*args, gchar *);
1687 /* Ignore empty elements */
1696 (*start == '\\' || *start == '/'))
1698 current_separator = *start;
1703 end = start + strlen (start);
1707 while (end >= start + 1 &&
1708 (end[-1] == '\\' || end[-1] == '/'))
1710 current_separator = end[-1];
1714 last_trailing = end;
1715 while (last_trailing >= element + 1 &&
1716 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1721 /* If the leading and trailing separator strings are in the
1722 * same element and overlap, the result is exactly that element
1724 if (last_trailing <= start)
1725 single_element = element;
1727 g_string_append_len (result, element, start - element);
1728 have_leading = TRUE;
1731 single_element = NULL;
1738 g_string_append_len (result, ¤t_separator, 1);
1740 g_string_append_len (result, start, end - start);
1746 g_string_free (result, TRUE);
1747 return g_strdup (single_element);
1752 g_string_append (result, last_trailing);
1754 return g_string_free (result, FALSE);
1761 * g_build_filenamev:
1762 * @args: %NULL-terminated array of strings containing the path elements.
1764 * Behaves exactly like g_build_filename(), but takes the path elements
1765 * as a string array, instead of varargs. This function is mainly
1766 * meant for language bindings.
1768 * Return value: a newly-allocated string that must be freed with g_free().
1773 g_build_filenamev (gchar **args)
1778 str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1780 str = g_build_pathname_va (NULL, NULL, args);
1788 * @first_element: the first element in the path
1789 * @Varargs: remaining elements in path, terminated by %NULL
1791 * Creates a filename from a series of elements using the correct
1792 * separator for filenames.
1794 * On Unix, this function behaves identically to <literal>g_build_path
1795 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1797 * On Windows, it takes into account that either the backslash
1798 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1799 * as separator in filenames, but otherwise behaves as on Unix. When
1800 * file pathname separators need to be inserted, the one that last
1801 * previously occurred in the parameters (reading from left to right)
1804 * No attempt is made to force the resulting filename to be an absolute
1805 * path. If the first element is a relative path, the result will
1806 * be a relative path.
1808 * Return value: a newly-allocated string that must be freed with g_free().
1811 g_build_filename (const gchar *first_element,
1817 va_start (args, first_element);
1819 str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1821 str = g_build_pathname_va (first_element, &args, NULL);
1830 * @filename: the symbolic link
1831 * @error: return location for a #GError
1833 * Reads the contents of the symbolic link @filename like the POSIX
1834 * readlink() function. The returned string is in the encoding used
1835 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1837 * Returns: A newly allocated string with the contents of the symbolic link,
1838 * or %NULL if an error occurred.
1843 g_file_read_link (const gchar *filename,
1846 #ifdef HAVE_READLINK
1852 buffer = g_malloc (size);
1856 read_size = readlink (filename, buffer, size);
1857 if (read_size < 0) {
1858 int save_errno = errno;
1859 gchar *display_filename = g_filename_display_name (filename);
1864 g_file_error_from_errno (save_errno),
1865 _("Failed to read the symbolic link '%s': %s"),
1867 g_strerror (save_errno));
1868 g_free (display_filename);
1873 if (read_size < size)
1875 buffer[read_size] = 0;
1880 buffer = g_realloc (buffer, size);
1886 _("Symbolic links not supported"));
1892 #define __G_FILEUTILS_C__
1893 #include "galiasdef.c"