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>
45 #endif /* G_OS_WIN32 */
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 set_umask_permissions (int fd,
932 /* All of this function is just to work around the fact that
933 * there is no way to get the umask without changing it.
935 * We can't just change-and-reset the umask because that would
936 * lead to a race condition if another thread tried to change
937 * the umask in between the getting and the setting of the umask.
938 * So we have to do the whole thing in a child process.
951 g_file_error_from_errno (save_errno),
952 _("Could not change file mode: fork() failed: %s"),
953 g_strerror (save_errno));
960 mode_t mask = umask (0666);
963 if (fchmod (fd, 0666 & ~mask) == -1)
968 return TRUE; /* To quiet gcc */
976 if (waitpid (pid, &status, 0) == -1)
982 g_file_error_from_errno (save_errno),
983 _("Could not change file mode: waitpid() failed: %s"),
984 g_strerror (save_errno));
989 if (WIFEXITED (status))
991 save_errno = WEXITSTATUS (status);
1001 g_file_error_from_errno (save_errno),
1002 _("Could not change file mode: chmod() failed: %s"),
1003 g_strerror (save_errno));
1008 else if (WIFSIGNALED (status))
1012 G_FILE_ERROR_FAILED,
1013 _("Could not change file mode: Child terminated by signal: %s"),
1014 g_strsignal (WTERMSIG (status)));
1020 /* This shouldn't happen */
1023 G_FILE_ERROR_FAILED,
1024 _("Could not change file mode: Child terminated abnormally"));
1032 write_to_temp_file (const gchar *contents,
1034 const gchar *template,
1038 gchar *display_name;
1046 tmp_name = g_strdup_printf ("%s.XXXXXX", template);
1049 fd = g_mkstemp (tmp_name);
1050 display_name = g_filename_display_name (tmp_name);
1057 g_file_error_from_errno (save_errno),
1058 _("Failed to create file '%s': %s"),
1059 display_name, g_strerror (save_errno));
1064 if (!set_umask_permissions (fd, err))
1067 g_unlink (tmp_name);
1073 file = fdopen (fd, "wb");
1079 g_file_error_from_errno (save_errno),
1080 _("Failed to open file '%s' for writing: fdopen() failed: %s"),
1082 g_strerror (save_errno));
1085 g_unlink (tmp_name);
1096 n_written = fwrite (contents, 1, length, file);
1098 if (n_written < length)
1104 g_file_error_from_errno (save_errno),
1105 _("Failed to write file '%s': fwrite() failed: %s"),
1107 g_strerror (save_errno));
1110 g_unlink (tmp_name);
1117 if (fclose (file) == EOF)
1123 g_file_error_from_errno (save_errno),
1124 _("Failed to close file '%s': fclose() failed: %s"),
1126 g_strerror (save_errno));
1128 g_unlink (tmp_name);
1133 retval = g_strdup (tmp_name);
1137 g_free (display_name);
1143 * g_file_set_contents:
1144 * @filename: name of a file to write @contents to, in the GLib file name
1146 * @contents: string to write to the file
1147 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1148 * @error: return location for a #GError, or %NULL
1150 * Writes all of @contents to a file named @filename, with good error checking.
1151 * If a file called @filename already exists it will be overwritten.
1153 * This write is atomic in the sense that it is first written to a temporary
1154 * file which is then renamed to the final name. Notes:
1157 * On Unix, if @filename already exists hard links to @filename will break.
1158 * Also since the file is recreated, existing permissions, access control
1159 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1160 * the link itself will be replaced, not the linked file.
1163 * On Windows renaming a file will not remove an existing file with the
1164 * new name, so on Windows there is a race condition between the existing
1165 * file being removed and the temporary file being renamed.
1168 * On Windows there is no way to remove a file that is open to some
1169 * process, or mapped into memory. Thus, this function will fail if
1170 * @filename already exists and is open.
1174 * If the call was sucessful, it returns %TRUE. If the call was not successful,
1175 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1176 * Possible error codes are those in the #GFileError enumeration.
1178 * Return value: %TRUE on success, %FALSE if an error occurred
1183 g_file_set_contents (const gchar *filename,
1184 const gchar *contents,
1188 gchar *tmp_filename;
1190 GError *rename_error = NULL;
1192 g_return_val_if_fail (filename != NULL, FALSE);
1193 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1194 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1195 g_return_val_if_fail (length >= -1, FALSE);
1198 length = strlen (contents);
1200 tmp_filename = write_to_temp_file (contents, length, filename, error);
1208 if (!rename_file (tmp_filename, filename, &rename_error))
1212 g_unlink (tmp_filename);
1213 g_propagate_error (error, rename_error);
1217 #else /* G_OS_WIN32 */
1219 /* Renaming failed, but on Windows this may just mean
1220 * the file already exists. So if the target file
1221 * exists, try deleting it and do the rename again.
1223 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1225 g_unlink (tmp_filename);
1226 g_propagate_error (error, rename_error);
1231 g_error_free (rename_error);
1233 if (g_unlink (filename) == -1)
1235 gchar *display_filename = g_filename_display_name (filename);
1237 int save_errno = errno;
1241 g_file_error_from_errno (save_errno),
1242 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1244 g_strerror (save_errno));
1246 g_free (display_filename);
1247 g_unlink (tmp_filename);
1252 if (!rename_file (tmp_filename, filename, error))
1254 g_unlink (tmp_filename);
1265 g_free (tmp_filename);
1270 * mkstemp() implementation is from the GNU C library.
1271 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1275 * @tmpl: template filename
1277 * Opens a temporary file. See the mkstemp() documentation
1278 * on most UNIX-like systems. This is a portability wrapper, which simply calls
1279 * mkstemp() on systems that have it, and implements
1280 * it in GLib otherwise.
1282 * The parameter is a string that should match the rules for
1283 * mkstemp(), i.e. end in "XXXXXX". The X string will
1284 * be modified to form the name of a file that didn't exist.
1285 * The string should be in the GLib file name encoding. Most importantly,
1286 * on Windows it should be in UTF-8.
1288 * Return value: A file handle (as from open()) to the file
1289 * opened for reading and writing. The file is opened in binary mode
1290 * on platforms where there is a difference. The file handle should be
1291 * closed with close(). In case of errors, -1 is returned.
1294 g_mkstemp (gchar *tmpl)
1297 return mkstemp (tmpl);
1302 static const char letters[] =
1303 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1304 static const int NLETTERS = sizeof (letters) - 1;
1307 static int counter = 0;
1309 len = strlen (tmpl);
1310 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
1316 /* This is where the Xs start. */
1317 XXXXXX = &tmpl[len - 6];
1319 /* Get some more or less random data. */
1320 g_get_current_time (&tv);
1321 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1323 for (count = 0; count < 100; value += 7777, ++count)
1327 /* Fill in the random bits. */
1328 XXXXXX[0] = letters[v % NLETTERS];
1330 XXXXXX[1] = letters[v % NLETTERS];
1332 XXXXXX[2] = letters[v % NLETTERS];
1334 XXXXXX[3] = letters[v % NLETTERS];
1336 XXXXXX[4] = letters[v % NLETTERS];
1338 XXXXXX[5] = letters[v % NLETTERS];
1340 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1341 fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1345 else if (errno != EEXIST)
1346 /* Any other error will apply also to other names we might
1347 * try, and there are 2^32 or so of them, so give up now.
1352 /* We got out of the loop because we ran out of combinations to try. */
1362 /* Binary compatibility version. Not for newly compiled code. */
1365 g_mkstemp (gchar *tmpl)
1370 static const char letters[] =
1371 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1372 static const int NLETTERS = sizeof (letters) - 1;
1375 static int counter = 0;
1377 len = strlen (tmpl);
1378 if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
1384 /* This is where the Xs start. */
1385 XXXXXX = &tmpl[len - 6];
1387 /* Get some more or less random data. */
1388 g_get_current_time (&tv);
1389 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1391 for (count = 0; count < 100; value += 7777, ++count)
1395 /* Fill in the random bits. */
1396 XXXXXX[0] = letters[v % NLETTERS];
1398 XXXXXX[1] = letters[v % NLETTERS];
1400 XXXXXX[2] = letters[v % NLETTERS];
1402 XXXXXX[3] = letters[v % NLETTERS];
1404 XXXXXX[4] = letters[v % NLETTERS];
1406 XXXXXX[5] = letters[v % NLETTERS];
1408 /* This is the backward compatibility system codepage version,
1409 * thus use normal open().
1411 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1415 else if (errno != EEXIST)
1416 /* Any other error will apply also to other names we might
1417 * try, and there are 2^32 or so of them, so give up now.
1422 /* We got out of the loop because we ran out of combinations to try. */
1431 * @tmpl: Template for file name, as in g_mkstemp(), basename only
1432 * @name_used: location to store actual name used
1433 * @error: return location for a #GError
1435 * Opens a file for writing in the preferred directory for temporary
1436 * files (as returned by g_get_tmp_dir()).
1438 * @tmpl should be a string in the GLib file name encoding ending with
1439 * six 'X' characters, as the parameter to g_mkstemp() (or mkstemp()).
1440 * However, unlike these functions, the template should only be a
1441 * basename, no directory components are allowed. If template is
1442 * %NULL, a default template is used.
1444 * Note that in contrast to g_mkstemp() (and mkstemp())
1445 * @tmpl is not modified, and might thus be a read-only literal string.
1447 * The actual name used is returned in @name_used if non-%NULL. This
1448 * string should be freed with g_free() when not needed any longer.
1449 * The returned name is in the GLib file name encoding.
1451 * Return value: A file handle (as from open()) to
1452 * the file opened for reading and writing. The file is opened in binary
1453 * mode on platforms where there is a difference. The file handle should be
1454 * closed with close(). In case of errors, -1 is returned
1455 * and @error will be set.
1458 g_file_open_tmp (const gchar *tmpl,
1471 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1473 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1477 gchar *display_tmpl = g_filename_display_name (tmpl);
1484 G_FILE_ERROR_FAILED,
1485 _("Template '%s' invalid, should not contain a '%s'"),
1487 g_free (display_tmpl);
1492 if (strlen (tmpl) < 6 ||
1493 strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
1495 gchar *display_tmpl = g_filename_display_name (tmpl);
1498 G_FILE_ERROR_FAILED,
1499 _("Template '%s' doesn't end with XXXXXX"),
1501 g_free (display_tmpl);
1505 tmpdir = g_get_tmp_dir ();
1507 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1510 sep = G_DIR_SEPARATOR_S;
1512 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1514 retval = g_mkstemp (fulltemplate);
1518 int save_errno = errno;
1519 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1523 g_file_error_from_errno (save_errno),
1524 _("Failed to create file '%s': %s"),
1525 display_fulltemplate, g_strerror (save_errno));
1526 g_free (display_fulltemplate);
1527 g_free (fulltemplate);
1532 *name_used = fulltemplate;
1534 g_free (fulltemplate);
1541 #undef g_file_open_tmp
1543 /* Binary compatibility version. Not for newly compiled code. */
1546 g_file_open_tmp (const gchar *tmpl,
1550 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1551 gchar *utf8_name_used;
1554 if (utf8_tmpl == NULL)
1557 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1563 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1565 g_free (utf8_name_used);
1573 g_build_path_va (const gchar *separator,
1574 const gchar *first_element,
1579 gint separator_len = strlen (separator);
1580 gboolean is_first = TRUE;
1581 gboolean have_leading = FALSE;
1582 const gchar *single_element = NULL;
1583 const gchar *next_element;
1584 const gchar *last_trailing = NULL;
1587 result = g_string_new (NULL);
1590 next_element = str_array[i++];
1592 next_element = first_element;
1596 const gchar *element;
1602 element = next_element;
1604 next_element = str_array[i++];
1606 next_element = va_arg (args, gchar *);
1611 /* Ignore empty elements */
1620 strncmp (start, separator, separator_len) == 0)
1621 start += separator_len;
1624 end = start + strlen (start);
1628 while (end >= start + separator_len &&
1629 strncmp (end - separator_len, separator, separator_len) == 0)
1630 end -= separator_len;
1632 last_trailing = end;
1633 while (last_trailing >= element + separator_len &&
1634 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1635 last_trailing -= separator_len;
1639 /* If the leading and trailing separator strings are in the
1640 * same element and overlap, the result is exactly that element
1642 if (last_trailing <= start)
1643 single_element = element;
1645 g_string_append_len (result, element, start - element);
1646 have_leading = TRUE;
1649 single_element = NULL;
1656 g_string_append (result, separator);
1658 g_string_append_len (result, start, end - start);
1664 g_string_free (result, TRUE);
1665 return g_strdup (single_element);
1670 g_string_append (result, last_trailing);
1672 return g_string_free (result, FALSE);
1678 * @separator: a string used to separator the elements of the path.
1679 * @args: %NULL-terminated array of strings containing the path elements.
1681 * Behaves exactly like g_build_path(), but takes the path elements
1682 * as a string array, instead of varargs. This function is mainly
1683 * meant for language bindings.
1685 * Return value: a newly-allocated string that must be freed with g_free().
1690 g_build_pathv (const gchar *separator,
1698 return g_build_path_va (separator, NULL, va_args, args);
1704 * @separator: a string used to separator the elements of the path.
1705 * @first_element: the first element in the path
1706 * @Varargs: remaining elements in path, terminated by %NULL
1708 * Creates a path from a series of elements using @separator as the
1709 * separator between elements. At the boundary between two elements,
1710 * any trailing occurrences of separator in the first element, or
1711 * leading occurrences of separator in the second element are removed
1712 * and exactly one copy of the separator is inserted.
1714 * Empty elements are ignored.
1716 * The number of leading copies of the separator on the result is
1717 * the same as the number of leading copies of the separator on
1718 * the first non-empty element.
1720 * The number of trailing copies of the separator on the result is
1721 * the same as the number of trailing copies of the separator on
1722 * the last non-empty element. (Determination of the number of
1723 * trailing copies is done without stripping leading copies, so
1724 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1725 * has 1 trailing copy.)
1727 * However, if there is only a single non-empty element, and there
1728 * are no characters in that element not part of the leading or
1729 * trailing separators, then the result is exactly the original value
1732 * Other than for determination of the number of leading and trailing
1733 * copies of the separator, elements consisting only of copies
1734 * of the separator are ignored.
1736 * Return value: a newly-allocated string that must be freed with g_free().
1739 g_build_path (const gchar *separator,
1740 const gchar *first_element,
1746 g_return_val_if_fail (separator != NULL, NULL);
1748 va_start (args, first_element);
1749 str = g_build_path_va (separator, first_element, args, NULL);
1758 g_build_pathname_va (const gchar *first_element,
1762 /* Code copied from g_build_pathv(), and modified to use two
1763 * alternative single-character separators.
1766 gboolean is_first = TRUE;
1767 gboolean have_leading = FALSE;
1768 const gchar *single_element = NULL;
1769 const gchar *next_element;
1770 const gchar *last_trailing = NULL;
1771 gchar current_separator = '\\';
1774 result = g_string_new (NULL);
1777 next_element = str_array[i++];
1779 next_element = first_element;
1783 const gchar *element;
1789 element = next_element;
1791 next_element = str_array[i++];
1793 next_element = va_arg (args, gchar *);
1798 /* Ignore empty elements */
1807 (*start == '\\' || *start == '/'))
1809 current_separator = *start;
1814 end = start + strlen (start);
1818 while (end >= start + 1 &&
1819 (end[-1] == '\\' || end[-1] == '/'))
1821 current_separator = end[-1];
1825 last_trailing = end;
1826 while (last_trailing >= element + 1 &&
1827 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1832 /* If the leading and trailing separator strings are in the
1833 * same element and overlap, the result is exactly that element
1835 if (last_trailing <= start)
1836 single_element = element;
1838 g_string_append_len (result, element, start - element);
1839 have_leading = TRUE;
1842 single_element = NULL;
1849 g_string_append_len (result, ¤t_separator, 1);
1851 g_string_append_len (result, start, end - start);
1857 g_string_free (result, TRUE);
1858 return g_strdup (single_element);
1863 g_string_append (result, last_trailing);
1865 return g_string_free (result, FALSE);
1872 * g_build_filenamev:
1873 * @args: %NULL-terminated array of strings containing the path elements.
1875 * Behaves exactly like g_build_filename(), but takes the path elements
1876 * as a string array, instead of varargs. This function is mainly
1877 * meant for language bindings.
1879 * Return value: a newly-allocated string that must be freed with g_free().
1884 g_build_filenamev (gchar **args)
1890 str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, va_args, args);
1892 str = g_build_pathname_va (NULL, va_args, args);
1900 * @first_element: the first element in the path
1901 * @Varargs: remaining elements in path, terminated by %NULL
1903 * Creates a filename from a series of elements using the correct
1904 * separator for filenames.
1906 * On Unix, this function behaves identically to <literal>g_build_path
1907 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1909 * On Windows, it takes into account that either the backslash
1910 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1911 * as separator in filenames, but otherwise behaves as on Unix. When
1912 * file pathname separators need to be inserted, the one that last
1913 * previously occurred in the parameters (reading from left to right)
1916 * No attempt is made to force the resulting filename to be an absolute
1917 * path. If the first element is a relative path, the result will
1918 * be a relative path.
1920 * Return value: a newly-allocated string that must be freed with g_free().
1923 g_build_filename (const gchar *first_element,
1929 va_start (args, first_element);
1931 str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, args, NULL);
1933 str = g_build_pathname_va (first_element, args, NULL);
1942 * @filename: the symbolic link
1943 * @error: return location for a #GError
1945 * Reads the contents of the symbolic link @filename like the POSIX
1946 * readlink() function. The returned string is in the encoding used
1947 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1949 * Returns: A newly allocated string with the contents of the symbolic link,
1950 * or %NULL if an error occurred.
1955 g_file_read_link (const gchar *filename,
1958 #ifdef HAVE_READLINK
1964 buffer = g_malloc (size);
1968 read_size = readlink (filename, buffer, size);
1969 if (read_size < 0) {
1970 int save_errno = errno;
1971 gchar *display_filename = g_filename_display_name (filename);
1976 g_file_error_from_errno (save_errno),
1977 _("Failed to read the symbolic link '%s': %s"),
1979 g_strerror (save_errno));
1980 g_free (display_filename);
1985 if (read_size < size)
1987 buffer[read_size] = 0;
1992 buffer = g_realloc (buffer, size);
1998 _("Symbolic links not supported"));
2004 #define __G_FILEUTILS_C__
2005 #include "galiasdef.c"