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 safe to write to a file without being
156 * tricked into writing into a different location. It doesn't work!
158 * /* DON'T DO THIS */
159 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
161 * fd = g_open (filename, O_WRONLY);
162 * /* write to fd */
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
194 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
196 if (wfilename == NULL)
199 attributes = GetFileAttributesW (wfilename);
203 if (attributes == INVALID_FILE_ATTRIBUTES)
206 if (test & G_FILE_TEST_EXISTS)
209 if (test & G_FILE_TEST_IS_REGULAR)
210 return (attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0;
212 if (test & G_FILE_TEST_IS_DIR)
213 return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
215 if (test & G_FILE_TEST_IS_EXECUTABLE)
217 const gchar *lastdot = strrchr (filename, '.');
218 const gchar *pathext = NULL, *p;
224 if (_stricmp (lastdot, ".exe") == 0 ||
225 _stricmp (lastdot, ".cmd") == 0 ||
226 _stricmp (lastdot, ".bat") == 0 ||
227 _stricmp (lastdot, ".com") == 0)
230 /* Check if it is one of the types listed in %PATHEXT% */
232 pathext = g_getenv ("PATHEXT");
236 pathext = g_utf8_casefold (pathext, -1);
238 lastdot = g_utf8_casefold (lastdot, -1);
239 extlen = strlen (lastdot);
244 const gchar *q = strchr (p, ';');
247 if (extlen == q - p &&
248 memcmp (lastdot, p, extlen) == 0)
250 g_free ((gchar *) pathext);
251 g_free ((gchar *) lastdot);
260 g_free ((gchar *) pathext);
261 g_free ((gchar *) lastdot);
267 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
270 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
275 /* For root, on some POSIX systems, access (filename, X_OK)
276 * will succeed even if no executable bits are set on the
277 * file. We fall through to a stat test to avoid that.
281 test &= ~G_FILE_TEST_IS_EXECUTABLE;
283 if (test & G_FILE_TEST_IS_SYMLINK)
287 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
291 if (test & (G_FILE_TEST_IS_REGULAR |
293 G_FILE_TEST_IS_EXECUTABLE))
297 if (stat (filename, &s) == 0)
299 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
302 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
305 /* The extra test for root when access (file, X_OK) succeeds.
307 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
308 ((s.st_mode & S_IXOTH) ||
309 (s.st_mode & S_IXUSR) ||
310 (s.st_mode & S_IXGRP)))
319 #if defined (G_OS_WIN32) && !defined (_WIN64)
323 /* Binary compatibility version. Not for newly compiled code. */
326 g_file_test (const gchar *filename,
329 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
332 if (utf8_filename == NULL)
335 retval = g_file_test_utf8 (utf8_filename, test);
337 g_free (utf8_filename);
345 g_file_error_quark (void)
347 return g_quark_from_static_string ("g-file-error-quark");
351 * g_file_error_from_errno:
352 * @err_no: an "errno" value
354 * Gets a #GFileError constant based on the passed-in @errno.
355 * For example, if you pass in %EEXIST this function returns
356 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
357 * assume that all #GFileError values will exist.
359 * Normally a #GFileError value goes into a #GError returned
360 * from a function that manipulates files. So you would use
361 * g_file_error_from_errno() when constructing a #GError.
363 * Return value: #GFileError corresponding to the given @errno
366 g_file_error_from_errno (gint err_no)
372 return G_FILE_ERROR_EXIST;
378 return G_FILE_ERROR_ISDIR;
384 return G_FILE_ERROR_ACCES;
390 return G_FILE_ERROR_NAMETOOLONG;
396 return G_FILE_ERROR_NOENT;
402 return G_FILE_ERROR_NOTDIR;
408 return G_FILE_ERROR_NXIO;
414 return G_FILE_ERROR_NODEV;
420 return G_FILE_ERROR_ROFS;
426 return G_FILE_ERROR_TXTBSY;
432 return G_FILE_ERROR_FAULT;
438 return G_FILE_ERROR_LOOP;
444 return G_FILE_ERROR_NOSPC;
450 return G_FILE_ERROR_NOMEM;
456 return G_FILE_ERROR_MFILE;
462 return G_FILE_ERROR_NFILE;
468 return G_FILE_ERROR_BADF;
474 return G_FILE_ERROR_INVAL;
480 return G_FILE_ERROR_PIPE;
486 return G_FILE_ERROR_AGAIN;
492 return G_FILE_ERROR_INTR;
498 return G_FILE_ERROR_IO;
504 return G_FILE_ERROR_PERM;
510 return G_FILE_ERROR_NOSYS;
515 return G_FILE_ERROR_FAILED;
521 get_contents_stdio (const gchar *display_filename,
530 gsize total_bytes = 0;
531 gsize total_allocated = 0;
534 g_assert (f != NULL);
540 bytes = fread (buf, 1, sizeof (buf), f);
543 while ((total_bytes + bytes + 1) > total_allocated)
546 total_allocated *= 2;
548 total_allocated = MIN (bytes + 1, sizeof (buf));
550 tmp = g_try_realloc (str, total_allocated);
557 _("Could not allocate %lu bytes to read file \"%s\""),
558 (gulong) total_allocated,
571 g_file_error_from_errno (save_errno),
572 _("Error reading file '%s': %s"),
574 g_strerror (save_errno));
579 memcpy (str + total_bytes, buf, bytes);
581 if (total_bytes + bytes < total_bytes)
586 _("File \"%s\" is too large"),
592 total_bytes += bytes;
597 if (total_allocated == 0)
599 str = g_new (gchar, 1);
603 str[total_bytes] = '\0';
606 *length = total_bytes;
623 get_contents_regfile (const gchar *display_filename,
624 struct stat *stat_buf,
635 size = stat_buf->st_size;
637 alloc_size = size + 1;
638 buf = g_try_malloc (alloc_size);
645 _("Could not allocate %lu bytes to read file \"%s\""),
653 while (bytes_read < size)
657 rc = read (fd, buf + bytes_read, size - bytes_read);
663 int save_errno = errno;
668 g_file_error_from_errno (save_errno),
669 _("Failed to read from file '%s': %s"),
671 g_strerror (save_errno));
682 buf[bytes_read] = '\0';
685 *length = bytes_read;
701 get_contents_posix (const gchar *filename,
706 struct stat stat_buf;
708 gchar *display_filename = g_filename_display_name (filename);
710 /* O_BINARY useful on Cygwin */
711 fd = open (filename, O_RDONLY|O_BINARY);
715 int save_errno = errno;
719 g_file_error_from_errno (save_errno),
720 _("Failed to open file '%s': %s"),
722 g_strerror (save_errno));
723 g_free (display_filename);
728 /* I don't think this will ever fail, aside from ENOMEM, but. */
729 if (fstat (fd, &stat_buf) < 0)
731 int save_errno = errno;
736 g_file_error_from_errno (save_errno),
737 _("Failed to get attributes of file '%s': fstat() failed: %s"),
739 g_strerror (save_errno));
740 g_free (display_filename);
745 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
747 gboolean retval = get_contents_regfile (display_filename,
753 g_free (display_filename);
762 f = fdopen (fd, "r");
766 int save_errno = errno;
770 g_file_error_from_errno (save_errno),
771 _("Failed to open file '%s': fdopen() failed: %s"),
773 g_strerror (save_errno));
774 g_free (display_filename);
779 retval = get_contents_stdio (display_filename, f, contents, length, error);
780 g_free (display_filename);
786 #else /* G_OS_WIN32 */
789 get_contents_win32 (const gchar *filename,
796 gchar *display_filename = g_filename_display_name (filename);
799 f = g_fopen (filename, "rb");
806 g_file_error_from_errno (save_errno),
807 _("Failed to open file '%s': %s"),
809 g_strerror (save_errno));
810 g_free (display_filename);
815 retval = get_contents_stdio (display_filename, f, contents, length, error);
816 g_free (display_filename);
824 * g_file_get_contents:
825 * @filename: name of a file to read contents from, in the GLib file name encoding
826 * @contents: location to store an allocated string
827 * @length: location to store length in bytes of the contents, or %NULL
828 * @error: return location for a #GError, or %NULL
830 * Reads an entire file into allocated memory, with good error
833 * If the call was successful, it returns %TRUE and sets @contents to the file
834 * contents and @length to the length of the file contents in bytes. The string
835 * stored in @contents will be nul-terminated, so for text files you can pass
836 * %NULL for the @length argument. If the call was not successful, it returns
837 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
838 * codes are those in the #GFileError enumeration. In the error case,
839 * @contents is set to %NULL and @length is set to zero.
841 * Return value: %TRUE on success, %FALSE if an error occurred
844 g_file_get_contents (const gchar *filename,
849 g_return_val_if_fail (filename != NULL, FALSE);
850 g_return_val_if_fail (contents != NULL, FALSE);
857 return get_contents_win32 (filename, contents, length, error);
859 return get_contents_posix (filename, contents, length, error);
863 #if defined (G_OS_WIN32) && !defined (_WIN64)
865 #undef g_file_get_contents
867 /* Binary compatibility version. Not for newly compiled code. */
870 g_file_get_contents (const gchar *filename,
875 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
878 if (utf8_filename == NULL)
881 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
883 g_free (utf8_filename);
891 rename_file (const char *old_name,
892 const char *new_name,
896 if (g_rename (old_name, new_name) == -1)
898 int save_errno = errno;
899 gchar *display_old_name = g_filename_display_name (old_name);
900 gchar *display_new_name = g_filename_display_name (new_name);
904 g_file_error_from_errno (save_errno),
905 _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
908 g_strerror (save_errno));
910 g_free (display_old_name);
911 g_free (display_new_name);
920 write_to_temp_file (const gchar *contents,
922 const gchar *template,
934 tmp_name = g_strdup_printf ("%s.XXXXXX", template);
937 fd = create_temp_file (tmp_name, 0666);
940 display_name = g_filename_display_name (tmp_name);
946 g_file_error_from_errno (save_errno),
947 _("Failed to create file '%s': %s"),
948 display_name, g_strerror (save_errno));
954 file = fdopen (fd, "wb");
960 g_file_error_from_errno (save_errno),
961 _("Failed to open file '%s' for writing: fdopen() failed: %s"),
963 g_strerror (save_errno));
977 n_written = fwrite (contents, 1, length, file);
979 if (n_written < length)
985 g_file_error_from_errno (save_errno),
986 _("Failed to write file '%s': fwrite() failed: %s"),
988 g_strerror (save_errno));
998 if (fclose (file) == EOF)
1004 g_file_error_from_errno (save_errno),
1005 _("Failed to close file '%s': fclose() failed: %s"),
1007 g_strerror (save_errno));
1009 g_unlink (tmp_name);
1014 retval = g_strdup (tmp_name);
1018 g_free (display_name);
1024 * g_file_set_contents:
1025 * @filename: name of a file to write @contents to, in the GLib file name
1027 * @contents: string to write to the file
1028 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1029 * @error: return location for a #GError, or %NULL
1031 * Writes all of @contents to a file named @filename, with good error checking.
1032 * If a file called @filename already exists it will be overwritten.
1034 * This write is atomic in the sense that it is first written to a temporary
1035 * file which is then renamed to the final name. Notes:
1038 * On Unix, if @filename already exists hard links to @filename will break.
1039 * Also since the file is recreated, existing permissions, access control
1040 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1041 * the link itself will be replaced, not the linked file.
1044 * On Windows renaming a file will not remove an existing file with the
1045 * new name, so on Windows there is a race condition between the existing
1046 * file being removed and the temporary file being renamed.
1049 * On Windows there is no way to remove a file that is open to some
1050 * process, or mapped into memory. Thus, this function will fail if
1051 * @filename already exists and is open.
1055 * If the call was sucessful, it returns %TRUE. If the call was not successful,
1056 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1057 * Possible error codes are those in the #GFileError enumeration.
1059 * Return value: %TRUE on success, %FALSE if an error occurred
1064 g_file_set_contents (const gchar *filename,
1065 const gchar *contents,
1069 gchar *tmp_filename;
1071 GError *rename_error = NULL;
1073 g_return_val_if_fail (filename != NULL, FALSE);
1074 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1075 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1076 g_return_val_if_fail (length >= -1, FALSE);
1079 length = strlen (contents);
1081 tmp_filename = write_to_temp_file (contents, length, filename, error);
1089 if (!rename_file (tmp_filename, filename, &rename_error))
1093 g_unlink (tmp_filename);
1094 g_propagate_error (error, rename_error);
1098 #else /* G_OS_WIN32 */
1100 /* Renaming failed, but on Windows this may just mean
1101 * the file already exists. So if the target file
1102 * exists, try deleting it and do the rename again.
1104 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1106 g_unlink (tmp_filename);
1107 g_propagate_error (error, rename_error);
1112 g_error_free (rename_error);
1114 if (g_unlink (filename) == -1)
1116 gchar *display_filename = g_filename_display_name (filename);
1118 int save_errno = errno;
1122 g_file_error_from_errno (save_errno),
1123 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1125 g_strerror (save_errno));
1127 g_free (display_filename);
1128 g_unlink (tmp_filename);
1133 if (!rename_file (tmp_filename, filename, error))
1135 g_unlink (tmp_filename);
1146 g_free (tmp_filename);
1151 * create_temp_file based on the mkstemp implementation from the GNU C library.
1152 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1155 create_temp_file (gchar *tmpl,
1160 static const char letters[] =
1161 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1162 static const int NLETTERS = sizeof (letters) - 1;
1165 static int counter = 0;
1167 /* find the last occurrence of "XXXXXX" */
1168 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1170 if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1176 /* Get some more or less random data. */
1177 g_get_current_time (&tv);
1178 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1180 for (count = 0; count < 100; value += 7777, ++count)
1184 /* Fill in the random bits. */
1185 XXXXXX[0] = letters[v % NLETTERS];
1187 XXXXXX[1] = letters[v % NLETTERS];
1189 XXXXXX[2] = letters[v % NLETTERS];
1191 XXXXXX[3] = letters[v % NLETTERS];
1193 XXXXXX[4] = letters[v % NLETTERS];
1195 XXXXXX[5] = letters[v % NLETTERS];
1197 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1198 fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, permissions);
1202 else if (errno != EEXIST)
1203 /* Any other error will apply also to other names we might
1204 * try, and there are 2^32 or so of them, so give up now.
1209 /* We got out of the loop because we ran out of combinations to try. */
1216 * @tmpl: template filename
1218 * Opens a temporary file. See the mkstemp() documentation
1219 * on most UNIX-like systems.
1221 * The parameter is a string that should follow the rules for
1222 * mkstemp() templates, i.e. contain the string "XXXXXX".
1223 * g_mkstemp() is slightly more flexible than mkstemp()
1224 * in that the sequence does not have to occur at the very end of the
1225 * template. The X string will
1226 * be modified to form the name of a file that didn't exist.
1227 * The string should be in the GLib file name encoding. Most importantly,
1228 * on Windows it should be in UTF-8.
1230 * Return value: A file handle (as from open()) to the file
1231 * opened for reading and writing. The file is opened in binary mode
1232 * on platforms where there is a difference. The file handle should be
1233 * closed with close(). In case of errors, -1 is returned.
1236 g_mkstemp (gchar *tmpl)
1238 return create_temp_file (tmpl, 0600);
1241 #if defined (G_OS_WIN32) && !defined (_WIN64)
1245 /* Binary compatibility version. Not for newly compiled code. */
1248 g_mkstemp (gchar *tmpl)
1252 static const char letters[] =
1253 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1254 static const int NLETTERS = sizeof (letters) - 1;
1257 static int counter = 0;
1259 /* find the last occurrence of 'XXXXXX' */
1260 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1262 if (!XXXXXX || strcmp (XXXXXX, "XXXXXX"))
1268 /* Get some more or less random data. */
1269 g_get_current_time (&tv);
1270 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1272 for (count = 0; count < 100; value += 7777, ++count)
1276 /* Fill in the random bits. */
1277 XXXXXX[0] = letters[v % NLETTERS];
1279 XXXXXX[1] = letters[v % NLETTERS];
1281 XXXXXX[2] = letters[v % NLETTERS];
1283 XXXXXX[3] = letters[v % NLETTERS];
1285 XXXXXX[4] = letters[v % NLETTERS];
1287 XXXXXX[5] = letters[v % NLETTERS];
1289 /* This is the backward compatibility system codepage version,
1290 * thus use normal open().
1292 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1296 else if (errno != EEXIST)
1297 /* Any other error will apply also to other names we might
1298 * try, and there are 2^32 or so of them, so give up now.
1303 /* We got out of the loop because we ran out of combinations to try. */
1312 * @tmpl: Template for file name, as in g_mkstemp(), basename only,
1313 * or %NULL, to a default template
1314 * @name_used: location to store actual name used, or %NULL
1315 * @error: return location for a #GError
1317 * Opens a file for writing in the preferred directory for temporary
1318 * files (as returned by g_get_tmp_dir()).
1320 * @tmpl should be a string in the GLib file name encoding containing
1321 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1322 * However, unlike these functions, the template should only be a
1323 * basename, no directory components are allowed. If template is
1324 * %NULL, a default template is used.
1326 * Note that in contrast to g_mkstemp() (and mkstemp())
1327 * @tmpl is not modified, and might thus be a read-only literal string.
1329 * The actual name used is returned in @name_used if non-%NULL. This
1330 * string should be freed with g_free() when not needed any longer.
1331 * The returned name is in the GLib file name encoding.
1333 * Return value: A file handle (as from open()) to
1334 * the file opened for reading and writing. The file is opened in binary
1335 * mode on platforms where there is a difference. The file handle should be
1336 * closed with close(). In case of errors, -1 is returned
1337 * and @error will be set.
1340 g_file_open_tmp (const gchar *tmpl,
1353 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1355 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1359 gchar *display_tmpl = g_filename_display_name (tmpl);
1366 G_FILE_ERROR_FAILED,
1367 _("Template '%s' invalid, should not contain a '%s'"),
1369 g_free (display_tmpl);
1374 if (strstr (tmpl, "XXXXXX") == NULL)
1376 gchar *display_tmpl = g_filename_display_name (tmpl);
1379 G_FILE_ERROR_FAILED,
1380 _("Template '%s' doesn't contain XXXXXX"),
1382 g_free (display_tmpl);
1386 tmpdir = g_get_tmp_dir ();
1388 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1391 sep = G_DIR_SEPARATOR_S;
1393 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1395 retval = g_mkstemp (fulltemplate);
1399 int save_errno = errno;
1400 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1404 g_file_error_from_errno (save_errno),
1405 _("Failed to create file '%s': %s"),
1406 display_fulltemplate, g_strerror (save_errno));
1407 g_free (display_fulltemplate);
1408 g_free (fulltemplate);
1413 *name_used = fulltemplate;
1415 g_free (fulltemplate);
1420 #if defined (G_OS_WIN32) && !defined (_WIN64)
1422 #undef g_file_open_tmp
1424 /* Binary compatibility version. Not for newly compiled code. */
1427 g_file_open_tmp (const gchar *tmpl,
1431 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1432 gchar *utf8_name_used;
1435 if (utf8_tmpl == NULL)
1438 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1444 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1446 g_free (utf8_name_used);
1454 g_build_path_va (const gchar *separator,
1455 const gchar *first_element,
1460 gint separator_len = strlen (separator);
1461 gboolean is_first = TRUE;
1462 gboolean have_leading = FALSE;
1463 const gchar *single_element = NULL;
1464 const gchar *next_element;
1465 const gchar *last_trailing = NULL;
1468 result = g_string_new (NULL);
1471 next_element = str_array[i++];
1473 next_element = first_element;
1477 const gchar *element;
1483 element = next_element;
1485 next_element = str_array[i++];
1487 next_element = va_arg (*args, gchar *);
1492 /* Ignore empty elements */
1501 strncmp (start, separator, separator_len) == 0)
1502 start += separator_len;
1505 end = start + strlen (start);
1509 while (end >= start + separator_len &&
1510 strncmp (end - separator_len, separator, separator_len) == 0)
1511 end -= separator_len;
1513 last_trailing = end;
1514 while (last_trailing >= element + separator_len &&
1515 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1516 last_trailing -= separator_len;
1520 /* If the leading and trailing separator strings are in the
1521 * same element and overlap, the result is exactly that element
1523 if (last_trailing <= start)
1524 single_element = element;
1526 g_string_append_len (result, element, start - element);
1527 have_leading = TRUE;
1530 single_element = NULL;
1537 g_string_append (result, separator);
1539 g_string_append_len (result, start, end - start);
1545 g_string_free (result, TRUE);
1546 return g_strdup (single_element);
1551 g_string_append (result, last_trailing);
1553 return g_string_free (result, FALSE);
1559 * @separator: a string used to separator the elements of the path.
1560 * @args: %NULL-terminated array of strings containing the path elements.
1562 * Behaves exactly like g_build_path(), but takes the path elements
1563 * as a string array, instead of varargs. This function is mainly
1564 * meant for language bindings.
1566 * Return value: a newly-allocated string that must be freed with g_free().
1571 g_build_pathv (const gchar *separator,
1577 return g_build_path_va (separator, NULL, NULL, args);
1583 * @separator: a string used to separator the elements of the path.
1584 * @first_element: the first element in the path
1585 * @Varargs: remaining elements in path, terminated by %NULL
1587 * Creates a path from a series of elements using @separator as the
1588 * separator between elements. At the boundary between two elements,
1589 * any trailing occurrences of separator in the first element, or
1590 * leading occurrences of separator in the second element are removed
1591 * and exactly one copy of the separator is inserted.
1593 * Empty elements are ignored.
1595 * The number of leading copies of the separator on the result is
1596 * the same as the number of leading copies of the separator on
1597 * the first non-empty element.
1599 * The number of trailing copies of the separator on the result is
1600 * the same as the number of trailing copies of the separator on
1601 * the last non-empty element. (Determination of the number of
1602 * trailing copies is done without stripping leading copies, so
1603 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1604 * has 1 trailing copy.)
1606 * However, if there is only a single non-empty element, and there
1607 * are no characters in that element not part of the leading or
1608 * trailing separators, then the result is exactly the original value
1611 * Other than for determination of the number of leading and trailing
1612 * copies of the separator, elements consisting only of copies
1613 * of the separator are ignored.
1615 * Return value: a newly-allocated string that must be freed with g_free().
1618 g_build_path (const gchar *separator,
1619 const gchar *first_element,
1625 g_return_val_if_fail (separator != NULL, NULL);
1627 va_start (args, first_element);
1628 str = g_build_path_va (separator, first_element, &args, NULL);
1637 g_build_pathname_va (const gchar *first_element,
1641 /* Code copied from g_build_pathv(), and modified to use two
1642 * alternative single-character separators.
1645 gboolean is_first = TRUE;
1646 gboolean have_leading = FALSE;
1647 const gchar *single_element = NULL;
1648 const gchar *next_element;
1649 const gchar *last_trailing = NULL;
1650 gchar current_separator = '\\';
1653 result = g_string_new (NULL);
1656 next_element = str_array[i++];
1658 next_element = first_element;
1662 const gchar *element;
1668 element = next_element;
1670 next_element = str_array[i++];
1672 next_element = va_arg (*args, gchar *);
1677 /* Ignore empty elements */
1686 (*start == '\\' || *start == '/'))
1688 current_separator = *start;
1693 end = start + strlen (start);
1697 while (end >= start + 1 &&
1698 (end[-1] == '\\' || end[-1] == '/'))
1700 current_separator = end[-1];
1704 last_trailing = end;
1705 while (last_trailing >= element + 1 &&
1706 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1711 /* If the leading and trailing separator strings are in the
1712 * same element and overlap, the result is exactly that element
1714 if (last_trailing <= start)
1715 single_element = element;
1717 g_string_append_len (result, element, start - element);
1718 have_leading = TRUE;
1721 single_element = NULL;
1728 g_string_append_len (result, ¤t_separator, 1);
1730 g_string_append_len (result, start, end - start);
1736 g_string_free (result, TRUE);
1737 return g_strdup (single_element);
1742 g_string_append (result, last_trailing);
1744 return g_string_free (result, FALSE);
1751 * g_build_filenamev:
1752 * @args: %NULL-terminated array of strings containing the path elements.
1754 * Behaves exactly like g_build_filename(), but takes the path elements
1755 * as a string array, instead of varargs. This function is mainly
1756 * meant for language bindings.
1758 * Return value: a newly-allocated string that must be freed with g_free().
1763 g_build_filenamev (gchar **args)
1768 str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1770 str = g_build_pathname_va (NULL, NULL, args);
1778 * @first_element: the first element in the path
1779 * @Varargs: remaining elements in path, terminated by %NULL
1781 * Creates a filename from a series of elements using the correct
1782 * separator for filenames.
1784 * On Unix, this function behaves identically to <literal>g_build_path
1785 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1787 * On Windows, it takes into account that either the backslash
1788 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1789 * as separator in filenames, but otherwise behaves as on Unix. When
1790 * file pathname separators need to be inserted, the one that last
1791 * previously occurred in the parameters (reading from left to right)
1794 * No attempt is made to force the resulting filename to be an absolute
1795 * path. If the first element is a relative path, the result will
1796 * be a relative path.
1798 * Return value: a newly-allocated string that must be freed with g_free().
1801 g_build_filename (const gchar *first_element,
1807 va_start (args, first_element);
1809 str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1811 str = g_build_pathname_va (first_element, &args, NULL);
1818 #define KILOBYTE_FACTOR 1024.0
1819 #define MEGABYTE_FACTOR (1024.0 * 1024.0)
1820 #define GIGABYTE_FACTOR (1024.0 * 1024.0 * 1024.0)
1823 * g_format_size_for_display:
1824 * @size: a size in bytes.
1826 * Formats a size (for example the size of a file) into a human readable string.
1827 * Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed
1828 * rounded to the nearest tenth. E.g. the file size 3292528 bytes will be
1829 * converted into the string "3.1 MB".
1831 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
1833 * This string should be freed with g_free() when not needed any longer.
1835 * Returns: a newly-allocated formatted string containing a human readable
1841 g_format_size_for_display (goffset size)
1843 if (size < (goffset) KILOBYTE_FACTOR)
1844 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
1847 gdouble displayed_size;
1849 if (size < (goffset) MEGABYTE_FACTOR)
1851 displayed_size = (gdouble) size / KILOBYTE_FACTOR;
1852 return g_strdup_printf (_("%.1f KB"), displayed_size);
1854 else if (size < (goffset) GIGABYTE_FACTOR)
1856 displayed_size = (gdouble) size / MEGABYTE_FACTOR;
1857 return g_strdup_printf (_("%.1f MB"), displayed_size);
1861 displayed_size = (gdouble) size / GIGABYTE_FACTOR;
1862 return g_strdup_printf (_("%.1f GB"), displayed_size);
1870 * @filename: the symbolic link
1871 * @error: return location for a #GError
1873 * Reads the contents of the symbolic link @filename like the POSIX
1874 * readlink() function. The returned string is in the encoding used
1875 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1877 * Returns: A newly-allocated string with the contents of the symbolic link,
1878 * or %NULL if an error occurred.
1883 g_file_read_link (const gchar *filename,
1886 #ifdef HAVE_READLINK
1892 buffer = g_malloc (size);
1896 read_size = readlink (filename, buffer, size);
1897 if (read_size < 0) {
1898 int save_errno = errno;
1899 gchar *display_filename = g_filename_display_name (filename);
1904 g_file_error_from_errno (save_errno),
1905 _("Failed to read the symbolic link '%s': %s"),
1907 g_strerror (save_errno));
1908 g_free (display_filename);
1913 if (read_size < size)
1915 buffer[read_size] = 0;
1920 buffer = g_realloc (buffer, size);
1923 g_set_error_literal (error,
1926 _("Symbolic links not supported"));
1932 #define __G_FILEUTILS_C__
1933 #include "galiasdef.c"