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.
22 #include "glibconfig.h"
33 #include <sys/types.h>
41 #endif /* G_OS_WIN32 */
51 #include "gfileutils.h"
56 #ifdef __linux__ /* for btrfs check */
57 #include <linux/magic.h>
62 * g_mkdir_with_parents:
63 * @pathname: a pathname in the GLib file name encoding
64 * @mode: permissions to use for newly created directories
66 * Create a directory if it doesn't already exist. Create intermediate
67 * parent directories as needed, too.
69 * Returns: 0 if the directory already exists, or was successfully
70 * created. Returns -1 if an error occurred, with errno set.
75 g_mkdir_with_parents (const gchar *pathname,
80 if (pathname == NULL || *pathname == '\0')
86 fn = g_strdup (pathname);
88 if (g_path_is_absolute (fn))
89 p = (gchar *) g_path_skip_root (fn);
95 while (*p && !G_IS_DIR_SEPARATOR (*p))
103 if (!g_file_test (fn, G_FILE_TEST_EXISTS))
105 if (g_mkdir (fn, mode) == -1)
107 int errno_save = errno;
113 else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
121 *p++ = G_DIR_SEPARATOR;
122 while (*p && G_IS_DIR_SEPARATOR (*p))
135 * @filename: a filename to test in the GLib file name encoding
136 * @test: bitfield of #GFileTest flags
138 * Returns %TRUE if any of the tests in the bitfield @test are
139 * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS |
140 * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists;
141 * the check whether it's a directory doesn't matter since the existence
142 * test is %TRUE. With the current set of available tests, there's no point
143 * passing in more than one test at a time.
145 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
146 * so for a symbolic link to a regular file g_file_test() will return
147 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
149 * Note, that for a dangling symbolic link g_file_test() will return
150 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
152 * You should never use g_file_test() to test whether it is safe
153 * to perform an operation, because there is always the possibility
154 * of the condition changing before you actually perform the operation.
155 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
156 * to know whether it is safe to write to a file without being
157 * tricked into writing into a different location. It doesn't work!
159 * /* DON'T DO THIS */
160 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
162 * fd = g_open (filename, O_WRONLY);
163 * /* write to fd */
167 * Another thing to note is that %G_FILE_TEST_EXISTS and
168 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
169 * system call. This usually doesn't matter, but if your program
170 * is setuid or setgid it means that these tests will give you
171 * the answer for the real user ID and group ID, rather than the
172 * effective user ID and group ID.
174 * On Windows, there are no symlinks, so testing for
175 * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
176 * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
177 * its name indicates that it is executable, checking for well-known
178 * extensions and those listed in the %PATHEXT environment variable.
180 * Return value: whether a test was %TRUE
183 g_file_test (const gchar *filename,
187 /* stuff missing in std vc6 api */
188 # ifndef INVALID_FILE_ATTRIBUTES
189 # define INVALID_FILE_ATTRIBUTES -1
191 # ifndef FILE_ATTRIBUTE_DEVICE
192 # define FILE_ATTRIBUTE_DEVICE 64
195 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
197 if (wfilename == NULL)
200 attributes = GetFileAttributesW (wfilename);
204 if (attributes == INVALID_FILE_ATTRIBUTES)
207 if (test & G_FILE_TEST_EXISTS)
210 if (test & G_FILE_TEST_IS_REGULAR)
212 if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0)
216 if (test & G_FILE_TEST_IS_DIR)
218 if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
222 /* "while" so that we can exit this "loop" with a simple "break" */
223 while (test & G_FILE_TEST_IS_EXECUTABLE)
225 const gchar *lastdot = strrchr (filename, '.');
226 const gchar *pathext = NULL, *p;
232 if (_stricmp (lastdot, ".exe") == 0 ||
233 _stricmp (lastdot, ".cmd") == 0 ||
234 _stricmp (lastdot, ".bat") == 0 ||
235 _stricmp (lastdot, ".com") == 0)
238 /* Check if it is one of the types listed in %PATHEXT% */
240 pathext = g_getenv ("PATHEXT");
244 pathext = g_utf8_casefold (pathext, -1);
246 lastdot = g_utf8_casefold (lastdot, -1);
247 extlen = strlen (lastdot);
252 const gchar *q = strchr (p, ';');
255 if (extlen == q - p &&
256 memcmp (lastdot, p, extlen) == 0)
258 g_free ((gchar *) pathext);
259 g_free ((gchar *) lastdot);
268 g_free ((gchar *) pathext);
269 g_free ((gchar *) lastdot);
275 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
278 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
283 /* For root, on some POSIX systems, access (filename, X_OK)
284 * will succeed even if no executable bits are set on the
285 * file. We fall through to a stat test to avoid that.
289 test &= ~G_FILE_TEST_IS_EXECUTABLE;
291 if (test & G_FILE_TEST_IS_SYMLINK)
295 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
299 if (test & (G_FILE_TEST_IS_REGULAR |
301 G_FILE_TEST_IS_EXECUTABLE))
305 if (stat (filename, &s) == 0)
307 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
310 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
313 /* The extra test for root when access (file, X_OK) succeeds.
315 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
316 ((s.st_mode & S_IXOTH) ||
317 (s.st_mode & S_IXUSR) ||
318 (s.st_mode & S_IXGRP)))
328 g_file_error_quark (void)
330 return g_quark_from_static_string ("g-file-error-quark");
334 * g_file_error_from_errno:
335 * @err_no: an "errno" value
337 * Gets a #GFileError constant based on the passed-in @errno.
338 * For example, if you pass in %EEXIST this function returns
339 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
340 * assume that all #GFileError values will exist.
342 * Normally a #GFileError value goes into a #GError returned
343 * from a function that manipulates files. So you would use
344 * g_file_error_from_errno() when constructing a #GError.
346 * Return value: #GFileError corresponding to the given @errno
349 g_file_error_from_errno (gint err_no)
355 return G_FILE_ERROR_EXIST;
361 return G_FILE_ERROR_ISDIR;
367 return G_FILE_ERROR_ACCES;
373 return G_FILE_ERROR_NAMETOOLONG;
379 return G_FILE_ERROR_NOENT;
385 return G_FILE_ERROR_NOTDIR;
391 return G_FILE_ERROR_NXIO;
397 return G_FILE_ERROR_NODEV;
403 return G_FILE_ERROR_ROFS;
409 return G_FILE_ERROR_TXTBSY;
415 return G_FILE_ERROR_FAULT;
421 return G_FILE_ERROR_LOOP;
427 return G_FILE_ERROR_NOSPC;
433 return G_FILE_ERROR_NOMEM;
439 return G_FILE_ERROR_MFILE;
445 return G_FILE_ERROR_NFILE;
451 return G_FILE_ERROR_BADF;
457 return G_FILE_ERROR_INVAL;
463 return G_FILE_ERROR_PIPE;
469 return G_FILE_ERROR_AGAIN;
475 return G_FILE_ERROR_INTR;
481 return G_FILE_ERROR_IO;
487 return G_FILE_ERROR_PERM;
493 return G_FILE_ERROR_NOSYS;
498 return G_FILE_ERROR_FAILED;
504 get_contents_stdio (const gchar *display_filename,
513 gsize total_bytes = 0;
514 gsize total_allocated = 0;
517 g_assert (f != NULL);
523 bytes = fread (buf, 1, sizeof (buf), f);
526 while ((total_bytes + bytes + 1) > total_allocated)
529 total_allocated *= 2;
531 total_allocated = MIN (bytes + 1, sizeof (buf));
533 tmp = g_try_realloc (str, total_allocated);
540 _("Could not allocate %lu bytes to read file \"%s\""),
541 (gulong) total_allocated,
554 g_file_error_from_errno (save_errno),
555 _("Error reading file '%s': %s"),
557 g_strerror (save_errno));
562 memcpy (str + total_bytes, buf, bytes);
564 if (total_bytes + bytes < total_bytes)
569 _("File \"%s\" is too large"),
575 total_bytes += bytes;
580 if (total_allocated == 0)
582 str = g_new (gchar, 1);
586 str[total_bytes] = '\0';
589 *length = total_bytes;
606 get_contents_regfile (const gchar *display_filename,
607 struct stat *stat_buf,
618 size = stat_buf->st_size;
620 alloc_size = size + 1;
621 buf = g_try_malloc (alloc_size);
628 _("Could not allocate %lu bytes to read file \"%s\""),
636 while (bytes_read < size)
640 rc = read (fd, buf + bytes_read, size - bytes_read);
646 int save_errno = errno;
651 g_file_error_from_errno (save_errno),
652 _("Failed to read from file '%s': %s"),
654 g_strerror (save_errno));
665 buf[bytes_read] = '\0';
668 *length = bytes_read;
684 get_contents_posix (const gchar *filename,
689 struct stat stat_buf;
691 gchar *display_filename = g_filename_display_name (filename);
693 /* O_BINARY useful on Cygwin */
694 fd = open (filename, O_RDONLY|O_BINARY);
698 int save_errno = errno;
702 g_file_error_from_errno (save_errno),
703 _("Failed to open file '%s': %s"),
705 g_strerror (save_errno));
706 g_free (display_filename);
711 /* I don't think this will ever fail, aside from ENOMEM, but. */
712 if (fstat (fd, &stat_buf) < 0)
714 int save_errno = errno;
719 g_file_error_from_errno (save_errno),
720 _("Failed to get attributes of file '%s': fstat() failed: %s"),
722 g_strerror (save_errno));
723 g_free (display_filename);
728 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
730 gboolean retval = get_contents_regfile (display_filename,
736 g_free (display_filename);
745 f = fdopen (fd, "r");
749 int save_errno = errno;
753 g_file_error_from_errno (save_errno),
754 _("Failed to open file '%s': fdopen() failed: %s"),
756 g_strerror (save_errno));
757 g_free (display_filename);
762 retval = get_contents_stdio (display_filename, f, contents, length, error);
763 g_free (display_filename);
769 #else /* G_OS_WIN32 */
772 get_contents_win32 (const gchar *filename,
779 gchar *display_filename = g_filename_display_name (filename);
782 f = g_fopen (filename, "rb");
789 g_file_error_from_errno (save_errno),
790 _("Failed to open file '%s': %s"),
792 g_strerror (save_errno));
793 g_free (display_filename);
798 retval = get_contents_stdio (display_filename, f, contents, length, error);
799 g_free (display_filename);
807 * g_file_get_contents:
808 * @filename: name of a file to read contents from, in the GLib file name encoding
809 * @contents: location to store an allocated string, use g_free() to free
810 * the returned string
811 * @length: location to store length in bytes of the contents, or %NULL
812 * @error: return location for a #GError, or %NULL
814 * Reads an entire file into allocated memory, with good error
817 * If the call was successful, it returns %TRUE and sets @contents to the file
818 * contents and @length to the length of the file contents in bytes. The string
819 * stored in @contents will be nul-terminated, so for text files you can pass
820 * %NULL for the @length argument. If the call was not successful, it returns
821 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
822 * codes are those in the #GFileError enumeration. In the error case,
823 * @contents is set to %NULL and @length is set to zero.
825 * Return value: %TRUE on success, %FALSE if an error occurred
828 g_file_get_contents (const gchar *filename,
833 g_return_val_if_fail (filename != NULL, FALSE);
834 g_return_val_if_fail (contents != NULL, FALSE);
841 return get_contents_win32 (filename, contents, length, error);
843 return get_contents_posix (filename, contents, length, error);
848 rename_file (const char *old_name,
849 const char *new_name,
853 if (g_rename (old_name, new_name) == -1)
855 int save_errno = errno;
856 gchar *display_old_name = g_filename_display_name (old_name);
857 gchar *display_new_name = g_filename_display_name (new_name);
861 g_file_error_from_errno (save_errno),
862 _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
865 g_strerror (save_errno));
867 g_free (display_old_name);
868 g_free (display_new_name);
877 write_to_temp_file (const gchar *contents,
879 const gchar *dest_file,
891 tmp_name = g_strdup_printf ("%s.XXXXXX", dest_file);
894 fd = g_mkstemp_full (tmp_name, O_RDWR | O_BINARY, 0666);
897 display_name = g_filename_display_name (tmp_name);
903 g_file_error_from_errno (save_errno),
904 _("Failed to create file '%s': %s"),
905 display_name, g_strerror (save_errno));
911 file = fdopen (fd, "wb");
917 g_file_error_from_errno (save_errno),
918 _("Failed to open file '%s' for writing: fdopen() failed: %s"),
920 g_strerror (save_errno));
934 n_written = fwrite (contents, 1, length, file);
936 if (n_written < length)
942 g_file_error_from_errno (save_errno),
943 _("Failed to write file '%s': fwrite() failed: %s"),
945 g_strerror (save_errno));
955 if (fflush (file) != 0)
961 g_file_error_from_errno (save_errno),
962 _("Failed to write file '%s': fflush() failed: %s"),
964 g_strerror (save_errno));
971 #ifdef BTRFS_SUPER_MAGIC
975 /* On Linux, on btrfs, skip the fsync since rename-over-existing is
976 * guaranteed to be atomic and this is the only case in which we
977 * would fsync() anyway.
980 if (fstatfs (fd, &buf) == 0 && buf.f_type == BTRFS_SUPER_MAGIC)
990 /* If the final destination exists and is > 0 bytes, we want to sync the
991 * newly written file to ensure the data is on disk when we rename over
992 * the destination. Otherwise if we get a system crash we can lose both
993 * the new and the old file on some filesystems. (I.E. those that don't
994 * guarantee the data is written to the disk before the metadata.)
996 if (g_lstat (dest_file, &statbuf) == 0 &&
997 statbuf.st_size > 0 &&
998 fsync (fileno (file)) != 0)
1004 g_file_error_from_errno (save_errno),
1005 _("Failed to write file '%s': fsync() failed: %s"),
1007 g_strerror (save_errno));
1009 g_unlink (tmp_name);
1018 if (fclose (file) == EOF)
1024 g_file_error_from_errno (save_errno),
1025 _("Failed to close file '%s': fclose() failed: %s"),
1027 g_strerror (save_errno));
1029 g_unlink (tmp_name);
1034 retval = g_strdup (tmp_name);
1038 g_free (display_name);
1044 * g_file_set_contents:
1045 * @filename: name of a file to write @contents to, in the GLib file name
1047 * @contents: string to write to the file
1048 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1049 * @error: return location for a #GError, or %NULL
1051 * Writes all of @contents to a file named @filename, with good error checking.
1052 * If a file called @filename already exists it will be overwritten.
1054 * This write is atomic in the sense that it is first written to a temporary
1055 * file which is then renamed to the final name. Notes:
1058 * On Unix, if @filename already exists hard links to @filename will break.
1059 * Also since the file is recreated, existing permissions, access control
1060 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1061 * the link itself will be replaced, not the linked file.
1064 * On Windows renaming a file will not remove an existing file with the
1065 * new name, so on Windows there is a race condition between the existing
1066 * file being removed and the temporary file being renamed.
1069 * On Windows there is no way to remove a file that is open to some
1070 * process, or mapped into memory. Thus, this function will fail if
1071 * @filename already exists and is open.
1075 * If the call was sucessful, it returns %TRUE. If the call was not successful,
1076 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1077 * Possible error codes are those in the #GFileError enumeration.
1079 * Note that the name for the temporary file is constructed by appending up
1080 * to 7 characters to @filename.
1082 * Return value: %TRUE on success, %FALSE if an error occurred
1087 g_file_set_contents (const gchar *filename,
1088 const gchar *contents,
1092 gchar *tmp_filename;
1094 GError *rename_error = NULL;
1096 g_return_val_if_fail (filename != NULL, FALSE);
1097 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1098 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1099 g_return_val_if_fail (length >= -1, FALSE);
1102 length = strlen (contents);
1104 tmp_filename = write_to_temp_file (contents, length, filename, error);
1112 if (!rename_file (tmp_filename, filename, &rename_error))
1116 g_unlink (tmp_filename);
1117 g_propagate_error (error, rename_error);
1121 #else /* G_OS_WIN32 */
1123 /* Renaming failed, but on Windows this may just mean
1124 * the file already exists. So if the target file
1125 * exists, try deleting it and do the rename again.
1127 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1129 g_unlink (tmp_filename);
1130 g_propagate_error (error, rename_error);
1135 g_error_free (rename_error);
1137 if (g_unlink (filename) == -1)
1139 gchar *display_filename = g_filename_display_name (filename);
1141 int save_errno = errno;
1145 g_file_error_from_errno (save_errno),
1146 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1148 g_strerror (save_errno));
1150 g_free (display_filename);
1151 g_unlink (tmp_filename);
1156 if (!rename_file (tmp_filename, filename, error))
1158 g_unlink (tmp_filename);
1169 g_free (tmp_filename);
1175 * @tmpl: template filename
1176 * @flags: flags to pass to an open() call in addition to O_EXCL and
1177 * O_CREAT, which are passed automatically
1178 * @mode: permissios to create the temporary file with
1180 * Opens a temporary file. See the mkstemp() documentation
1181 * on most UNIX-like systems.
1183 * The parameter is a string that should follow the rules for
1184 * mkstemp() templates, i.e. contain the string "XXXXXX".
1185 * g_mkstemp_full() is slightly more flexible than mkstemp()
1186 * in that the sequence does not have to occur at the very end of the
1187 * template and you can pass a @mode and additional @flags. The X
1188 * string will be modified to form the name of a file that didn't exist.
1189 * The string should be in the GLib file name encoding. Most importantly,
1190 * on Windows it should be in UTF-8.
1192 * Return value: A file handle (as from open()) to the file
1193 * opened for reading and writing. The file handle should be
1194 * closed with close(). In case of errors, -1 is returned.
1199 * g_mkstemp_full based on the mkstemp implementation from the GNU C library.
1200 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1203 g_mkstemp_full (gchar *tmpl,
1209 static const char letters[] =
1210 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1211 static const int NLETTERS = sizeof (letters) - 1;
1214 static int counter = 0;
1216 g_return_val_if_fail (tmpl != NULL, -1);
1219 /* find the last occurrence of "XXXXXX" */
1220 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1222 if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1228 /* Get some more or less random data. */
1229 g_get_current_time (&tv);
1230 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1232 for (count = 0; count < 100; value += 7777, ++count)
1236 /* Fill in the random bits. */
1237 XXXXXX[0] = letters[v % NLETTERS];
1239 XXXXXX[1] = letters[v % NLETTERS];
1241 XXXXXX[2] = letters[v % NLETTERS];
1243 XXXXXX[3] = letters[v % NLETTERS];
1245 XXXXXX[4] = letters[v % NLETTERS];
1247 XXXXXX[5] = letters[v % NLETTERS];
1249 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1250 fd = g_open (tmpl, flags | O_CREAT | O_EXCL, mode);
1254 else if (errno != EEXIST)
1255 /* Any other error will apply also to other names we might
1256 * try, and there are 2^32 or so of them, so give up now.
1261 /* We got out of the loop because we ran out of combinations to try. */
1268 * @tmpl: template filename
1270 * Opens a temporary file. See the mkstemp() documentation
1271 * on most UNIX-like systems.
1273 * The parameter is a string that should follow the rules for
1274 * mkstemp() templates, i.e. contain the string "XXXXXX".
1275 * g_mkstemp() is slightly more flexible than mkstemp()
1276 * in that the sequence does not have to occur at the very end of the
1277 * template. The X string will
1278 * be modified to form the name of a file that didn't exist.
1279 * The string should be in the GLib file name encoding. Most importantly,
1280 * on Windows it should be in UTF-8.
1282 * Return value: A file handle (as from open()) to the file
1283 * opened for reading and writing. The file is opened in binary mode
1284 * on platforms where there is a difference. The file handle should be
1285 * closed with close(). In case of errors, -1 is returned.
1288 g_mkstemp (gchar *tmpl)
1290 return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1295 * @tmpl: Template for file name, as in g_mkstemp(), basename only,
1296 * or %NULL, to a default template
1297 * @name_used: location to store actual name used, or %NULL
1298 * @error: return location for a #GError
1300 * Opens a file for writing in the preferred directory for temporary
1301 * files (as returned by g_get_tmp_dir()).
1303 * @tmpl should be a string in the GLib file name encoding containing
1304 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1305 * However, unlike these functions, the template should only be a
1306 * basename, no directory components are allowed. If template is
1307 * %NULL, a default template is used.
1309 * Note that in contrast to g_mkstemp() (and mkstemp())
1310 * @tmpl is not modified, and might thus be a read-only literal string.
1312 * The actual name used is returned in @name_used if non-%NULL. This
1313 * string should be freed with g_free() when not needed any longer.
1314 * The returned name is in the GLib file name encoding.
1316 * Return value: A file handle (as from open()) to
1317 * the file opened for reading and writing. The file is opened in binary
1318 * mode on platforms where there is a difference. The file handle should be
1319 * closed with close(). In case of errors, -1 is returned
1320 * and @error will be set.
1323 g_file_open_tmp (const gchar *tmpl,
1336 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1338 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1342 gchar *display_tmpl = g_filename_display_name (tmpl);
1349 G_FILE_ERROR_FAILED,
1350 _("Template '%s' invalid, should not contain a '%s'"),
1352 g_free (display_tmpl);
1357 if (strstr (tmpl, "XXXXXX") == NULL)
1359 gchar *display_tmpl = g_filename_display_name (tmpl);
1362 G_FILE_ERROR_FAILED,
1363 _("Template '%s' doesn't contain XXXXXX"),
1365 g_free (display_tmpl);
1369 tmpdir = g_get_tmp_dir ();
1371 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1374 sep = G_DIR_SEPARATOR_S;
1376 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1378 retval = g_mkstemp (fulltemplate);
1382 int save_errno = errno;
1383 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1387 g_file_error_from_errno (save_errno),
1388 _("Failed to create file '%s': %s"),
1389 display_fulltemplate, g_strerror (save_errno));
1390 g_free (display_fulltemplate);
1391 g_free (fulltemplate);
1396 *name_used = fulltemplate;
1398 g_free (fulltemplate);
1404 g_build_path_va (const gchar *separator,
1405 const gchar *first_element,
1410 gint separator_len = strlen (separator);
1411 gboolean is_first = TRUE;
1412 gboolean have_leading = FALSE;
1413 const gchar *single_element = NULL;
1414 const gchar *next_element;
1415 const gchar *last_trailing = NULL;
1418 result = g_string_new (NULL);
1421 next_element = str_array[i++];
1423 next_element = first_element;
1427 const gchar *element;
1433 element = next_element;
1435 next_element = str_array[i++];
1437 next_element = va_arg (*args, gchar *);
1442 /* Ignore empty elements */
1450 while (strncmp (start, separator, separator_len) == 0)
1451 start += separator_len;
1454 end = start + strlen (start);
1458 while (end >= start + separator_len &&
1459 strncmp (end - separator_len, separator, separator_len) == 0)
1460 end -= separator_len;
1462 last_trailing = end;
1463 while (last_trailing >= element + separator_len &&
1464 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1465 last_trailing -= separator_len;
1469 /* If the leading and trailing separator strings are in the
1470 * same element and overlap, the result is exactly that element
1472 if (last_trailing <= start)
1473 single_element = element;
1475 g_string_append_len (result, element, start - element);
1476 have_leading = TRUE;
1479 single_element = NULL;
1486 g_string_append (result, separator);
1488 g_string_append_len (result, start, end - start);
1494 g_string_free (result, TRUE);
1495 return g_strdup (single_element);
1500 g_string_append (result, last_trailing);
1502 return g_string_free (result, FALSE);
1508 * @separator: a string used to separator the elements of the path.
1509 * @args: %NULL-terminated array of strings containing the path elements.
1511 * Behaves exactly like g_build_path(), but takes the path elements
1512 * as a string array, instead of varargs. This function is mainly
1513 * meant for language bindings.
1515 * Return value: a newly-allocated string that must be freed with g_free().
1520 g_build_pathv (const gchar *separator,
1526 return g_build_path_va (separator, NULL, NULL, args);
1532 * @separator: a string used to separator the elements of the path.
1533 * @first_element: the first element in the path
1534 * @Varargs: remaining elements in path, terminated by %NULL
1536 * Creates a path from a series of elements using @separator as the
1537 * separator between elements. At the boundary between two elements,
1538 * any trailing occurrences of separator in the first element, or
1539 * leading occurrences of separator in the second element are removed
1540 * and exactly one copy of the separator is inserted.
1542 * Empty elements are ignored.
1544 * The number of leading copies of the separator on the result is
1545 * the same as the number of leading copies of the separator on
1546 * the first non-empty element.
1548 * The number of trailing copies of the separator on the result is
1549 * the same as the number of trailing copies of the separator on
1550 * the last non-empty element. (Determination of the number of
1551 * trailing copies is done without stripping leading copies, so
1552 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1553 * has 1 trailing copy.)
1555 * However, if there is only a single non-empty element, and there
1556 * are no characters in that element not part of the leading or
1557 * trailing separators, then the result is exactly the original value
1560 * Other than for determination of the number of leading and trailing
1561 * copies of the separator, elements consisting only of copies
1562 * of the separator are ignored.
1564 * Return value: a newly-allocated string that must be freed with g_free().
1567 g_build_path (const gchar *separator,
1568 const gchar *first_element,
1574 g_return_val_if_fail (separator != NULL, NULL);
1576 va_start (args, first_element);
1577 str = g_build_path_va (separator, first_element, &args, NULL);
1586 g_build_pathname_va (const gchar *first_element,
1590 /* Code copied from g_build_pathv(), and modified to use two
1591 * alternative single-character separators.
1594 gboolean is_first = TRUE;
1595 gboolean have_leading = FALSE;
1596 const gchar *single_element = NULL;
1597 const gchar *next_element;
1598 const gchar *last_trailing = NULL;
1599 gchar current_separator = '\\';
1602 result = g_string_new (NULL);
1605 next_element = str_array[i++];
1607 next_element = first_element;
1611 const gchar *element;
1617 element = next_element;
1619 next_element = str_array[i++];
1621 next_element = va_arg (*args, gchar *);
1626 /* Ignore empty elements */
1635 (*start == '\\' || *start == '/'))
1637 current_separator = *start;
1642 end = start + strlen (start);
1646 while (end >= start + 1 &&
1647 (end[-1] == '\\' || end[-1] == '/'))
1649 current_separator = end[-1];
1653 last_trailing = end;
1654 while (last_trailing >= element + 1 &&
1655 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1660 /* If the leading and trailing separator strings are in the
1661 * same element and overlap, the result is exactly that element
1663 if (last_trailing <= start)
1664 single_element = element;
1666 g_string_append_len (result, element, start - element);
1667 have_leading = TRUE;
1670 single_element = NULL;
1677 g_string_append_len (result, ¤t_separator, 1);
1679 g_string_append_len (result, start, end - start);
1685 g_string_free (result, TRUE);
1686 return g_strdup (single_element);
1691 g_string_append (result, last_trailing);
1693 return g_string_free (result, FALSE);
1700 * g_build_filenamev:
1701 * @args: %NULL-terminated array of strings containing the path elements.
1703 * Behaves exactly like g_build_filename(), but takes the path elements
1704 * as a string array, instead of varargs. This function is mainly
1705 * meant for language bindings.
1707 * Return value: a newly-allocated string that must be freed with g_free().
1712 g_build_filenamev (gchar **args)
1717 str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1719 str = g_build_pathname_va (NULL, NULL, args);
1727 * @first_element: the first element in the path
1728 * @Varargs: remaining elements in path, terminated by %NULL
1730 * Creates a filename from a series of elements using the correct
1731 * separator for filenames.
1733 * On Unix, this function behaves identically to <literal>g_build_path
1734 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1736 * On Windows, it takes into account that either the backslash
1737 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1738 * as separator in filenames, but otherwise behaves as on Unix. When
1739 * file pathname separators need to be inserted, the one that last
1740 * previously occurred in the parameters (reading from left to right)
1743 * No attempt is made to force the resulting filename to be an absolute
1744 * path. If the first element is a relative path, the result will
1745 * be a relative path.
1747 * Return value: a newly-allocated string that must be freed with g_free().
1750 g_build_filename (const gchar *first_element,
1756 va_start (args, first_element);
1758 str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1760 str = g_build_pathname_va (first_element, &args, NULL);
1767 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
1768 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
1769 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
1770 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
1771 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
1772 #define EXABYTE_FACTOR (PETABYTE_FACTOR * KILOBYTE_FACTOR)
1775 * g_format_size_for_display:
1776 * @size: a size in bytes.
1778 * Formats a size (for example the size of a file) into a human readable string.
1779 * Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed
1780 * rounded to the nearest tenth. E.g. the file size 3292528 bytes will be
1781 * converted into the string "3.1 MB".
1783 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
1785 * This string should be freed with g_free() when not needed any longer.
1787 * Returns: a newly-allocated formatted string containing a human readable
1793 g_format_size_for_display (goffset size)
1795 if (size < (goffset) KILOBYTE_FACTOR)
1796 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
1799 gdouble displayed_size;
1801 if (size < (goffset) MEGABYTE_FACTOR)
1803 displayed_size = (gdouble) size / (gdouble) KILOBYTE_FACTOR;
1804 return g_strdup_printf (_("%.1f KB"), displayed_size);
1806 else if (size < (goffset) GIGABYTE_FACTOR)
1808 displayed_size = (gdouble) size / (gdouble) MEGABYTE_FACTOR;
1809 return g_strdup_printf (_("%.1f MB"), displayed_size);
1811 else if (size < (goffset) TERABYTE_FACTOR)
1813 displayed_size = (gdouble) size / (gdouble) GIGABYTE_FACTOR;
1814 return g_strdup_printf (_("%.1f GB"), displayed_size);
1816 else if (size < (goffset) PETABYTE_FACTOR)
1818 displayed_size = (gdouble) size / (gdouble) TERABYTE_FACTOR;
1819 return g_strdup_printf (_("%.1f TB"), displayed_size);
1821 else if (size < (goffset) EXABYTE_FACTOR)
1823 displayed_size = (gdouble) size / (gdouble) PETABYTE_FACTOR;
1824 return g_strdup_printf (_("%.1f PB"), displayed_size);
1828 displayed_size = (gdouble) size / (gdouble) EXABYTE_FACTOR;
1829 return g_strdup_printf (_("%.1f EB"), displayed_size);
1837 * @filename: the symbolic link
1838 * @error: return location for a #GError
1840 * Reads the contents of the symbolic link @filename like the POSIX
1841 * readlink() function. The returned string is in the encoding used
1842 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1844 * Returns: A newly-allocated string with the contents of the symbolic link,
1845 * or %NULL if an error occurred.
1850 g_file_read_link (const gchar *filename,
1853 #ifdef HAVE_READLINK
1859 buffer = g_malloc (size);
1863 read_size = readlink (filename, buffer, size);
1864 if (read_size < 0) {
1865 int save_errno = errno;
1866 gchar *display_filename = g_filename_display_name (filename);
1871 g_file_error_from_errno (save_errno),
1872 _("Failed to read the symbolic link '%s': %s"),
1874 g_strerror (save_errno));
1875 g_free (display_filename);
1880 if (read_size < size)
1882 buffer[read_size] = 0;
1887 buffer = g_realloc (buffer, size);
1890 g_set_error_literal (error,
1893 _("Symbolic links not supported"));
1899 /* NOTE : Keep this part last to ensure nothing in this file uses the
1900 * below binary compatibility versions.
1902 #if defined (G_OS_WIN32) && !defined (_WIN64)
1904 /* Binary compatibility versions. Will be called by code compiled
1905 * against quite old (pre-2.8, I think) headers only, not from more
1906 * recently compiled code.
1912 g_file_test (const gchar *filename,
1915 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
1918 if (utf8_filename == NULL)
1921 retval = g_file_test_utf8 (utf8_filename, test);
1923 g_free (utf8_filename);
1928 #undef g_file_get_contents
1931 g_file_get_contents (const gchar *filename,
1936 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
1939 if (utf8_filename == NULL)
1942 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
1944 g_free (utf8_filename);
1952 g_mkstemp (gchar *tmpl)
1956 static const char letters[] =
1957 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1958 static const int NLETTERS = sizeof (letters) - 1;
1961 static int counter = 0;
1963 /* find the last occurrence of 'XXXXXX' */
1964 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1972 /* Get some more or less random data. */
1973 g_get_current_time (&tv);
1974 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1976 for (count = 0; count < 100; value += 7777, ++count)
1980 /* Fill in the random bits. */
1981 XXXXXX[0] = letters[v % NLETTERS];
1983 XXXXXX[1] = letters[v % NLETTERS];
1985 XXXXXX[2] = letters[v % NLETTERS];
1987 XXXXXX[3] = letters[v % NLETTERS];
1989 XXXXXX[4] = letters[v % NLETTERS];
1991 XXXXXX[5] = letters[v % NLETTERS];
1993 /* This is the backward compatibility system codepage version,
1994 * thus use normal open().
1996 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
2000 else if (errno != EEXIST)
2001 /* Any other error will apply also to other names we might
2002 * try, and there are 2^32 or so of them, so give up now.
2007 /* We got out of the loop because we ran out of combinations to try. */
2012 #undef g_file_open_tmp
2015 g_file_open_tmp (const gchar *tmpl,
2019 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
2020 gchar *utf8_name_used;
2023 if (utf8_tmpl == NULL)
2026 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
2032 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
2034 g_free (utf8_name_used);