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 */
58 * g_mkdir_with_parents:
59 * @pathname: a pathname in the GLib file name encoding
60 * @mode: permissions to use for newly created directories
62 * Create a directory if it doesn't already exist. Create intermediate
63 * parent directories as needed, too.
65 * Returns: 0 if the directory already exists, or was successfully
66 * created. Returns -1 if an error occurred, with errno set.
71 g_mkdir_with_parents (const gchar *pathname,
76 if (pathname == NULL || *pathname == '\0')
82 fn = g_strdup (pathname);
84 if (g_path_is_absolute (fn))
85 p = (gchar *) g_path_skip_root (fn);
91 while (*p && !G_IS_DIR_SEPARATOR (*p))
99 if (!g_file_test (fn, G_FILE_TEST_EXISTS))
101 if (g_mkdir (fn, mode) == -1)
103 int errno_save = errno;
109 else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
117 *p++ = G_DIR_SEPARATOR;
118 while (*p && G_IS_DIR_SEPARATOR (*p))
131 * @filename: a filename to test in the GLib file name encoding
132 * @test: bitfield of #GFileTest flags
134 * Returns %TRUE if any of the tests in the bitfield @test are
135 * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS |
136 * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists;
137 * the check whether it's a directory doesn't matter since the existence
138 * test is %TRUE. With the current set of available tests, there's no point
139 * passing in more than one test at a time.
141 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
142 * so for a symbolic link to a regular file g_file_test() will return
143 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
145 * Note, that for a dangling symbolic link g_file_test() will return
146 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
148 * You should never use g_file_test() to test whether it is safe
149 * to perform an operation, because there is always the possibility
150 * of the condition changing before you actually perform the operation.
151 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
152 * to know whether it is safe to write to a file without being
153 * tricked into writing into a different location. It doesn't work!
155 * /* DON'T DO THIS */
156 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
158 * fd = g_open (filename, O_WRONLY);
159 * /* write to fd */
163 * Another thing to note is that %G_FILE_TEST_EXISTS and
164 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
165 * system call. This usually doesn't matter, but if your program
166 * is setuid or setgid it means that these tests will give you
167 * the answer for the real user ID and group ID, rather than the
168 * effective user ID and group ID.
170 * On Windows, there are no symlinks, so testing for
171 * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
172 * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
173 * its name indicates that it is executable, checking for well-known
174 * extensions and those listed in the %PATHEXT environment variable.
176 * Return value: whether a test was %TRUE
179 g_file_test (const gchar *filename,
183 /* stuff missing in std vc6 api */
184 # ifndef INVALID_FILE_ATTRIBUTES
185 # define INVALID_FILE_ATTRIBUTES -1
187 # ifndef FILE_ATTRIBUTE_DEVICE
188 # define FILE_ATTRIBUTE_DEVICE 64
191 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
193 if (wfilename == NULL)
196 attributes = GetFileAttributesW (wfilename);
200 if (attributes == INVALID_FILE_ATTRIBUTES)
203 if (test & G_FILE_TEST_EXISTS)
206 if (test & G_FILE_TEST_IS_REGULAR)
207 return (attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0;
209 if (test & G_FILE_TEST_IS_DIR)
210 return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
212 if (test & G_FILE_TEST_IS_EXECUTABLE)
214 const gchar *lastdot = strrchr (filename, '.');
215 const gchar *pathext = NULL, *p;
221 if (_stricmp (lastdot, ".exe") == 0 ||
222 _stricmp (lastdot, ".cmd") == 0 ||
223 _stricmp (lastdot, ".bat") == 0 ||
224 _stricmp (lastdot, ".com") == 0)
227 /* Check if it is one of the types listed in %PATHEXT% */
229 pathext = g_getenv ("PATHEXT");
233 pathext = g_utf8_casefold (pathext, -1);
235 lastdot = g_utf8_casefold (lastdot, -1);
236 extlen = strlen (lastdot);
241 const gchar *q = strchr (p, ';');
244 if (extlen == q - p &&
245 memcmp (lastdot, p, extlen) == 0)
247 g_free ((gchar *) pathext);
248 g_free ((gchar *) lastdot);
257 g_free ((gchar *) pathext);
258 g_free ((gchar *) lastdot);
264 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
267 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
272 /* For root, on some POSIX systems, access (filename, X_OK)
273 * will succeed even if no executable bits are set on the
274 * file. We fall through to a stat test to avoid that.
278 test &= ~G_FILE_TEST_IS_EXECUTABLE;
280 if (test & G_FILE_TEST_IS_SYMLINK)
284 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
288 if (test & (G_FILE_TEST_IS_REGULAR |
290 G_FILE_TEST_IS_EXECUTABLE))
294 if (stat (filename, &s) == 0)
296 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
299 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
302 /* The extra test for root when access (file, X_OK) succeeds.
304 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
305 ((s.st_mode & S_IXOTH) ||
306 (s.st_mode & S_IXUSR) ||
307 (s.st_mode & S_IXGRP)))
317 g_file_error_quark (void)
319 return g_quark_from_static_string ("g-file-error-quark");
323 * g_file_error_from_errno:
324 * @err_no: an "errno" value
326 * Gets a #GFileError constant based on the passed-in @errno.
327 * For example, if you pass in %EEXIST this function returns
328 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
329 * assume that all #GFileError values will exist.
331 * Normally a #GFileError value goes into a #GError returned
332 * from a function that manipulates files. So you would use
333 * g_file_error_from_errno() when constructing a #GError.
335 * Return value: #GFileError corresponding to the given @errno
338 g_file_error_from_errno (gint err_no)
344 return G_FILE_ERROR_EXIST;
350 return G_FILE_ERROR_ISDIR;
356 return G_FILE_ERROR_ACCES;
362 return G_FILE_ERROR_NAMETOOLONG;
368 return G_FILE_ERROR_NOENT;
374 return G_FILE_ERROR_NOTDIR;
380 return G_FILE_ERROR_NXIO;
386 return G_FILE_ERROR_NODEV;
392 return G_FILE_ERROR_ROFS;
398 return G_FILE_ERROR_TXTBSY;
404 return G_FILE_ERROR_FAULT;
410 return G_FILE_ERROR_LOOP;
416 return G_FILE_ERROR_NOSPC;
422 return G_FILE_ERROR_NOMEM;
428 return G_FILE_ERROR_MFILE;
434 return G_FILE_ERROR_NFILE;
440 return G_FILE_ERROR_BADF;
446 return G_FILE_ERROR_INVAL;
452 return G_FILE_ERROR_PIPE;
458 return G_FILE_ERROR_AGAIN;
464 return G_FILE_ERROR_INTR;
470 return G_FILE_ERROR_IO;
476 return G_FILE_ERROR_PERM;
482 return G_FILE_ERROR_NOSYS;
487 return G_FILE_ERROR_FAILED;
493 get_contents_stdio (const gchar *display_filename,
502 gsize total_bytes = 0;
503 gsize total_allocated = 0;
506 g_assert (f != NULL);
512 bytes = fread (buf, 1, sizeof (buf), f);
515 while ((total_bytes + bytes + 1) > total_allocated)
518 total_allocated *= 2;
520 total_allocated = MIN (bytes + 1, sizeof (buf));
522 tmp = g_try_realloc (str, total_allocated);
529 _("Could not allocate %lu bytes to read file \"%s\""),
530 (gulong) total_allocated,
543 g_file_error_from_errno (save_errno),
544 _("Error reading file '%s': %s"),
546 g_strerror (save_errno));
551 memcpy (str + total_bytes, buf, bytes);
553 if (total_bytes + bytes < total_bytes)
558 _("File \"%s\" is too large"),
564 total_bytes += bytes;
569 if (total_allocated == 0)
571 str = g_new (gchar, 1);
575 str[total_bytes] = '\0';
578 *length = total_bytes;
595 get_contents_regfile (const gchar *display_filename,
596 struct stat *stat_buf,
607 size = stat_buf->st_size;
609 alloc_size = size + 1;
610 buf = g_try_malloc (alloc_size);
617 _("Could not allocate %lu bytes to read file \"%s\""),
625 while (bytes_read < size)
629 rc = read (fd, buf + bytes_read, size - bytes_read);
635 int save_errno = errno;
640 g_file_error_from_errno (save_errno),
641 _("Failed to read from file '%s': %s"),
643 g_strerror (save_errno));
654 buf[bytes_read] = '\0';
657 *length = bytes_read;
673 get_contents_posix (const gchar *filename,
678 struct stat stat_buf;
680 gchar *display_filename = g_filename_display_name (filename);
682 /* O_BINARY useful on Cygwin */
683 fd = open (filename, O_RDONLY|O_BINARY);
687 int save_errno = errno;
691 g_file_error_from_errno (save_errno),
692 _("Failed to open file '%s': %s"),
694 g_strerror (save_errno));
695 g_free (display_filename);
700 /* I don't think this will ever fail, aside from ENOMEM, but. */
701 if (fstat (fd, &stat_buf) < 0)
703 int save_errno = errno;
708 g_file_error_from_errno (save_errno),
709 _("Failed to get attributes of file '%s': fstat() failed: %s"),
711 g_strerror (save_errno));
712 g_free (display_filename);
717 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
719 gboolean retval = get_contents_regfile (display_filename,
725 g_free (display_filename);
734 f = fdopen (fd, "r");
738 int save_errno = errno;
742 g_file_error_from_errno (save_errno),
743 _("Failed to open file '%s': fdopen() failed: %s"),
745 g_strerror (save_errno));
746 g_free (display_filename);
751 retval = get_contents_stdio (display_filename, f, contents, length, error);
752 g_free (display_filename);
758 #else /* G_OS_WIN32 */
761 get_contents_win32 (const gchar *filename,
768 gchar *display_filename = g_filename_display_name (filename);
771 f = g_fopen (filename, "rb");
778 g_file_error_from_errno (save_errno),
779 _("Failed to open file '%s': %s"),
781 g_strerror (save_errno));
782 g_free (display_filename);
787 retval = get_contents_stdio (display_filename, f, contents, length, error);
788 g_free (display_filename);
796 * g_file_get_contents:
797 * @filename: name of a file to read contents from, in the GLib file name encoding
798 * @contents: location to store an allocated string, use g_free() to free
799 * the returned string
800 * @length: location to store length in bytes of the contents, or %NULL
801 * @error: return location for a #GError, or %NULL
803 * Reads an entire file into allocated memory, with good error
806 * If the call was successful, it returns %TRUE and sets @contents to the file
807 * contents and @length to the length of the file contents in bytes. The string
808 * stored in @contents will be nul-terminated, so for text files you can pass
809 * %NULL for the @length argument. If the call was not successful, it returns
810 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
811 * codes are those in the #GFileError enumeration. In the error case,
812 * @contents is set to %NULL and @length is set to zero.
814 * Return value: %TRUE on success, %FALSE if an error occurred
817 g_file_get_contents (const gchar *filename,
822 g_return_val_if_fail (filename != NULL, FALSE);
823 g_return_val_if_fail (contents != NULL, FALSE);
830 return get_contents_win32 (filename, contents, length, error);
832 return get_contents_posix (filename, contents, length, error);
837 rename_file (const char *old_name,
838 const char *new_name,
842 if (g_rename (old_name, new_name) == -1)
844 int save_errno = errno;
845 gchar *display_old_name = g_filename_display_name (old_name);
846 gchar *display_new_name = g_filename_display_name (new_name);
850 g_file_error_from_errno (save_errno),
851 _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
854 g_strerror (save_errno));
856 g_free (display_old_name);
857 g_free (display_new_name);
866 write_to_temp_file (const gchar *contents,
868 const gchar *dest_file,
880 tmp_name = g_strdup_printf ("%s.XXXXXX", dest_file);
883 fd = g_mkstemp_full (tmp_name, O_RDWR | O_BINARY, 0666);
886 display_name = g_filename_display_name (tmp_name);
892 g_file_error_from_errno (save_errno),
893 _("Failed to create file '%s': %s"),
894 display_name, g_strerror (save_errno));
900 file = fdopen (fd, "wb");
906 g_file_error_from_errno (save_errno),
907 _("Failed to open file '%s' for writing: fdopen() failed: %s"),
909 g_strerror (save_errno));
923 n_written = fwrite (contents, 1, length, file);
925 if (n_written < length)
931 g_file_error_from_errno (save_errno),
932 _("Failed to write file '%s': fwrite() failed: %s"),
934 g_strerror (save_errno));
944 if (fflush (file) != 0)
950 g_file_error_from_errno (save_errno),
951 _("Failed to write file '%s': fflush() failed: %s"),
953 g_strerror (save_errno));
965 /* If the final destination exists and is > 0 bytes, we want to sync the
966 * newly written file to ensure the data is on disk when we rename over
967 * the destination. Otherwise if we get a system crash we can lose both
968 * the new and the old file on some filesystems. (I.E. those that don't
969 * guarantee the data is written to the disk before the metadata.)
971 if (g_lstat (dest_file, &statbuf) == 0 &&
972 statbuf.st_size > 0 &&
973 fsync (fileno (file)) != 0)
979 g_file_error_from_errno (save_errno),
980 _("Failed to write file '%s': fsync() failed: %s"),
982 g_strerror (save_errno));
992 if (fclose (file) == EOF)
998 g_file_error_from_errno (save_errno),
999 _("Failed to close file '%s': fclose() failed: %s"),
1001 g_strerror (save_errno));
1003 g_unlink (tmp_name);
1008 retval = g_strdup (tmp_name);
1012 g_free (display_name);
1018 * g_file_set_contents:
1019 * @filename: name of a file to write @contents to, in the GLib file name
1021 * @contents: string to write to the file
1022 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1023 * @error: return location for a #GError, or %NULL
1025 * Writes all of @contents to a file named @filename, with good error checking.
1026 * If a file called @filename already exists it will be overwritten.
1028 * This write is atomic in the sense that it is first written to a temporary
1029 * file which is then renamed to the final name. Notes:
1032 * On Unix, if @filename already exists hard links to @filename will break.
1033 * Also since the file is recreated, existing permissions, access control
1034 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1035 * the link itself will be replaced, not the linked file.
1038 * On Windows renaming a file will not remove an existing file with the
1039 * new name, so on Windows there is a race condition between the existing
1040 * file being removed and the temporary file being renamed.
1043 * On Windows there is no way to remove a file that is open to some
1044 * process, or mapped into memory. Thus, this function will fail if
1045 * @filename already exists and is open.
1049 * If the call was sucessful, it returns %TRUE. If the call was not successful,
1050 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1051 * Possible error codes are those in the #GFileError enumeration.
1053 * Return value: %TRUE on success, %FALSE if an error occurred
1058 g_file_set_contents (const gchar *filename,
1059 const gchar *contents,
1063 gchar *tmp_filename;
1065 GError *rename_error = NULL;
1067 g_return_val_if_fail (filename != NULL, FALSE);
1068 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1069 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1070 g_return_val_if_fail (length >= -1, FALSE);
1073 length = strlen (contents);
1075 tmp_filename = write_to_temp_file (contents, length, filename, error);
1083 if (!rename_file (tmp_filename, filename, &rename_error))
1087 g_unlink (tmp_filename);
1088 g_propagate_error (error, rename_error);
1092 #else /* G_OS_WIN32 */
1094 /* Renaming failed, but on Windows this may just mean
1095 * the file already exists. So if the target file
1096 * exists, try deleting it and do the rename again.
1098 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1100 g_unlink (tmp_filename);
1101 g_propagate_error (error, rename_error);
1106 g_error_free (rename_error);
1108 if (g_unlink (filename) == -1)
1110 gchar *display_filename = g_filename_display_name (filename);
1112 int save_errno = errno;
1116 g_file_error_from_errno (save_errno),
1117 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1119 g_strerror (save_errno));
1121 g_free (display_filename);
1122 g_unlink (tmp_filename);
1127 if (!rename_file (tmp_filename, filename, error))
1129 g_unlink (tmp_filename);
1140 g_free (tmp_filename);
1146 * @tmpl: template filename
1147 * @flags: flags to pass to an open() call in addition to O_EXCL and
1148 * O_CREAT, which are passed automatically
1149 * @mode: permissios to create the temporary file with
1151 * Opens a temporary file. See the mkstemp() documentation
1152 * on most UNIX-like systems.
1154 * The parameter is a string that should follow the rules for
1155 * mkstemp() templates, i.e. contain the string "XXXXXX".
1156 * g_mkstemp_full() is slightly more flexible than mkstemp()
1157 * in that the sequence does not have to occur at the very end of the
1158 * template and you can pass a @mode and additional @flags. The X
1159 * string will be modified to form the name of a file that didn't exist.
1160 * The string should be in the GLib file name encoding. Most importantly,
1161 * on Windows it should be in UTF-8.
1163 * Return value: A file handle (as from open()) to the file
1164 * opened for reading and writing. The file handle should be
1165 * closed with close(). In case of errors, -1 is returned.
1170 * g_mkstemp_full based on the mkstemp implementation from the GNU C library.
1171 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1174 g_mkstemp_full (gchar *tmpl,
1180 static const char letters[] =
1181 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1182 static const int NLETTERS = sizeof (letters) - 1;
1185 static int counter = 0;
1187 g_return_val_if_fail (tmpl != NULL, -1);
1190 /* find the last occurrence of "XXXXXX" */
1191 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1193 if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1199 /* Get some more or less random data. */
1200 g_get_current_time (&tv);
1201 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1203 for (count = 0; count < 100; value += 7777, ++count)
1207 /* Fill in the random bits. */
1208 XXXXXX[0] = letters[v % NLETTERS];
1210 XXXXXX[1] = letters[v % NLETTERS];
1212 XXXXXX[2] = letters[v % NLETTERS];
1214 XXXXXX[3] = letters[v % NLETTERS];
1216 XXXXXX[4] = letters[v % NLETTERS];
1218 XXXXXX[5] = letters[v % NLETTERS];
1220 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1221 fd = g_open (tmpl, flags | O_CREAT | O_EXCL, mode);
1225 else if (errno != EEXIST)
1226 /* Any other error will apply also to other names we might
1227 * try, and there are 2^32 or so of them, so give up now.
1232 /* We got out of the loop because we ran out of combinations to try. */
1239 * @tmpl: template filename
1241 * Opens a temporary file. See the mkstemp() documentation
1242 * on most UNIX-like systems.
1244 * The parameter is a string that should follow the rules for
1245 * mkstemp() templates, i.e. contain the string "XXXXXX".
1246 * g_mkstemp() is slightly more flexible than mkstemp()
1247 * in that the sequence does not have to occur at the very end of the
1248 * template. The X string will
1249 * be modified to form the name of a file that didn't exist.
1250 * The string should be in the GLib file name encoding. Most importantly,
1251 * on Windows it should be in UTF-8.
1253 * Return value: A file handle (as from open()) to the file
1254 * opened for reading and writing. The file is opened in binary mode
1255 * on platforms where there is a difference. The file handle should be
1256 * closed with close(). In case of errors, -1 is returned.
1259 g_mkstemp (gchar *tmpl)
1261 return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1266 * @tmpl: Template for file name, as in g_mkstemp(), basename only,
1267 * or %NULL, to a default template
1268 * @name_used: location to store actual name used, or %NULL
1269 * @error: return location for a #GError
1271 * Opens a file for writing in the preferred directory for temporary
1272 * files (as returned by g_get_tmp_dir()).
1274 * @tmpl should be a string in the GLib file name encoding containing
1275 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1276 * However, unlike these functions, the template should only be a
1277 * basename, no directory components are allowed. If template is
1278 * %NULL, a default template is used.
1280 * Note that in contrast to g_mkstemp() (and mkstemp())
1281 * @tmpl is not modified, and might thus be a read-only literal string.
1283 * The actual name used is returned in @name_used if non-%NULL. This
1284 * string should be freed with g_free() when not needed any longer.
1285 * The returned name is in the GLib file name encoding.
1287 * Return value: A file handle (as from open()) to
1288 * the file opened for reading and writing. The file is opened in binary
1289 * mode on platforms where there is a difference. The file handle should be
1290 * closed with close(). In case of errors, -1 is returned
1291 * and @error will be set.
1294 g_file_open_tmp (const gchar *tmpl,
1307 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1309 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1313 gchar *display_tmpl = g_filename_display_name (tmpl);
1320 G_FILE_ERROR_FAILED,
1321 _("Template '%s' invalid, should not contain a '%s'"),
1323 g_free (display_tmpl);
1328 if (strstr (tmpl, "XXXXXX") == NULL)
1330 gchar *display_tmpl = g_filename_display_name (tmpl);
1333 G_FILE_ERROR_FAILED,
1334 _("Template '%s' doesn't contain XXXXXX"),
1336 g_free (display_tmpl);
1340 tmpdir = g_get_tmp_dir ();
1342 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1345 sep = G_DIR_SEPARATOR_S;
1347 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1349 retval = g_mkstemp (fulltemplate);
1353 int save_errno = errno;
1354 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1358 g_file_error_from_errno (save_errno),
1359 _("Failed to create file '%s': %s"),
1360 display_fulltemplate, g_strerror (save_errno));
1361 g_free (display_fulltemplate);
1362 g_free (fulltemplate);
1367 *name_used = fulltemplate;
1369 g_free (fulltemplate);
1375 g_build_path_va (const gchar *separator,
1376 const gchar *first_element,
1381 gint separator_len = strlen (separator);
1382 gboolean is_first = TRUE;
1383 gboolean have_leading = FALSE;
1384 const gchar *single_element = NULL;
1385 const gchar *next_element;
1386 const gchar *last_trailing = NULL;
1389 result = g_string_new (NULL);
1392 next_element = str_array[i++];
1394 next_element = first_element;
1398 const gchar *element;
1404 element = next_element;
1406 next_element = str_array[i++];
1408 next_element = va_arg (*args, gchar *);
1413 /* Ignore empty elements */
1421 while (strncmp (start, separator, separator_len) == 0)
1422 start += separator_len;
1425 end = start + strlen (start);
1429 while (end >= start + separator_len &&
1430 strncmp (end - separator_len, separator, separator_len) == 0)
1431 end -= separator_len;
1433 last_trailing = end;
1434 while (last_trailing >= element + separator_len &&
1435 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1436 last_trailing -= separator_len;
1440 /* If the leading and trailing separator strings are in the
1441 * same element and overlap, the result is exactly that element
1443 if (last_trailing <= start)
1444 single_element = element;
1446 g_string_append_len (result, element, start - element);
1447 have_leading = TRUE;
1450 single_element = NULL;
1457 g_string_append (result, separator);
1459 g_string_append_len (result, start, end - start);
1465 g_string_free (result, TRUE);
1466 return g_strdup (single_element);
1471 g_string_append (result, last_trailing);
1473 return g_string_free (result, FALSE);
1479 * @separator: a string used to separator the elements of the path.
1480 * @args: %NULL-terminated array of strings containing the path elements.
1482 * Behaves exactly like g_build_path(), but takes the path elements
1483 * as a string array, instead of varargs. This function is mainly
1484 * meant for language bindings.
1486 * Return value: a newly-allocated string that must be freed with g_free().
1491 g_build_pathv (const gchar *separator,
1497 return g_build_path_va (separator, NULL, NULL, args);
1503 * @separator: a string used to separator the elements of the path.
1504 * @first_element: the first element in the path
1505 * @Varargs: remaining elements in path, terminated by %NULL
1507 * Creates a path from a series of elements using @separator as the
1508 * separator between elements. At the boundary between two elements,
1509 * any trailing occurrences of separator in the first element, or
1510 * leading occurrences of separator in the second element are removed
1511 * and exactly one copy of the separator is inserted.
1513 * Empty elements are ignored.
1515 * The number of leading copies of the separator on the result is
1516 * the same as the number of leading copies of the separator on
1517 * the first non-empty element.
1519 * The number of trailing copies of the separator on the result is
1520 * the same as the number of trailing copies of the separator on
1521 * the last non-empty element. (Determination of the number of
1522 * trailing copies is done without stripping leading copies, so
1523 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1524 * has 1 trailing copy.)
1526 * However, if there is only a single non-empty element, and there
1527 * are no characters in that element not part of the leading or
1528 * trailing separators, then the result is exactly the original value
1531 * Other than for determination of the number of leading and trailing
1532 * copies of the separator, elements consisting only of copies
1533 * of the separator are ignored.
1535 * Return value: a newly-allocated string that must be freed with g_free().
1538 g_build_path (const gchar *separator,
1539 const gchar *first_element,
1545 g_return_val_if_fail (separator != NULL, NULL);
1547 va_start (args, first_element);
1548 str = g_build_path_va (separator, first_element, &args, NULL);
1557 g_build_pathname_va (const gchar *first_element,
1561 /* Code copied from g_build_pathv(), and modified to use two
1562 * alternative single-character separators.
1565 gboolean is_first = TRUE;
1566 gboolean have_leading = FALSE;
1567 const gchar *single_element = NULL;
1568 const gchar *next_element;
1569 const gchar *last_trailing = NULL;
1570 gchar current_separator = '\\';
1573 result = g_string_new (NULL);
1576 next_element = str_array[i++];
1578 next_element = first_element;
1582 const gchar *element;
1588 element = next_element;
1590 next_element = str_array[i++];
1592 next_element = va_arg (*args, gchar *);
1597 /* Ignore empty elements */
1606 (*start == '\\' || *start == '/'))
1608 current_separator = *start;
1613 end = start + strlen (start);
1617 while (end >= start + 1 &&
1618 (end[-1] == '\\' || end[-1] == '/'))
1620 current_separator = end[-1];
1624 last_trailing = end;
1625 while (last_trailing >= element + 1 &&
1626 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1631 /* If the leading and trailing separator strings are in the
1632 * same element and overlap, the result is exactly that element
1634 if (last_trailing <= start)
1635 single_element = element;
1637 g_string_append_len (result, element, start - element);
1638 have_leading = TRUE;
1641 single_element = NULL;
1648 g_string_append_len (result, ¤t_separator, 1);
1650 g_string_append_len (result, start, end - start);
1656 g_string_free (result, TRUE);
1657 return g_strdup (single_element);
1662 g_string_append (result, last_trailing);
1664 return g_string_free (result, FALSE);
1671 * g_build_filenamev:
1672 * @args: %NULL-terminated array of strings containing the path elements.
1674 * Behaves exactly like g_build_filename(), but takes the path elements
1675 * as a string array, instead of varargs. This function is mainly
1676 * meant for language bindings.
1678 * Return value: a newly-allocated string that must be freed with g_free().
1683 g_build_filenamev (gchar **args)
1688 str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1690 str = g_build_pathname_va (NULL, NULL, args);
1698 * @first_element: the first element in the path
1699 * @Varargs: remaining elements in path, terminated by %NULL
1701 * Creates a filename from a series of elements using the correct
1702 * separator for filenames.
1704 * On Unix, this function behaves identically to <literal>g_build_path
1705 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1707 * On Windows, it takes into account that either the backslash
1708 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1709 * as separator in filenames, but otherwise behaves as on Unix. When
1710 * file pathname separators need to be inserted, the one that last
1711 * previously occurred in the parameters (reading from left to right)
1714 * No attempt is made to force the resulting filename to be an absolute
1715 * path. If the first element is a relative path, the result will
1716 * be a relative path.
1718 * Return value: a newly-allocated string that must be freed with g_free().
1721 g_build_filename (const gchar *first_element,
1727 va_start (args, first_element);
1729 str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1731 str = g_build_pathname_va (first_element, &args, NULL);
1738 #define KILOBYTE_FACTOR 1024.0
1739 #define MEGABYTE_FACTOR (1024.0 * 1024.0)
1740 #define GIGABYTE_FACTOR (1024.0 * 1024.0 * 1024.0)
1743 * g_format_size_for_display:
1744 * @size: a size in bytes.
1746 * Formats a size (for example the size of a file) into a human readable string.
1747 * Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed
1748 * rounded to the nearest tenth. E.g. the file size 3292528 bytes will be
1749 * converted into the string "3.1 MB".
1751 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
1753 * This string should be freed with g_free() when not needed any longer.
1755 * Returns: a newly-allocated formatted string containing a human readable
1761 g_format_size_for_display (goffset size)
1763 if (size < (goffset) KILOBYTE_FACTOR)
1764 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
1767 gdouble displayed_size;
1769 if (size < (goffset) MEGABYTE_FACTOR)
1771 displayed_size = (gdouble) size / KILOBYTE_FACTOR;
1772 return g_strdup_printf (_("%.1f KB"), displayed_size);
1774 else if (size < (goffset) GIGABYTE_FACTOR)
1776 displayed_size = (gdouble) size / MEGABYTE_FACTOR;
1777 return g_strdup_printf (_("%.1f MB"), displayed_size);
1781 displayed_size = (gdouble) size / GIGABYTE_FACTOR;
1782 return g_strdup_printf (_("%.1f GB"), displayed_size);
1790 * @filename: the symbolic link
1791 * @error: return location for a #GError
1793 * Reads the contents of the symbolic link @filename like the POSIX
1794 * readlink() function. The returned string is in the encoding used
1795 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1797 * Returns: A newly-allocated string with the contents of the symbolic link,
1798 * or %NULL if an error occurred.
1803 g_file_read_link (const gchar *filename,
1806 #ifdef HAVE_READLINK
1812 buffer = g_malloc (size);
1816 read_size = readlink (filename, buffer, size);
1817 if (read_size < 0) {
1818 int save_errno = errno;
1819 gchar *display_filename = g_filename_display_name (filename);
1824 g_file_error_from_errno (save_errno),
1825 _("Failed to read the symbolic link '%s': %s"),
1827 g_strerror (save_errno));
1828 g_free (display_filename);
1833 if (read_size < size)
1835 buffer[read_size] = 0;
1840 buffer = g_realloc (buffer, size);
1843 g_set_error_literal (error,
1846 _("Symbolic links not supported"));
1852 /* NOTE : Keep this part last to ensure nothing in this file uses the
1853 * below binary compatibility versions.
1855 #if defined (G_OS_WIN32) && !defined (_WIN64)
1857 /* Binary compatibility versions. Will be called by code compiled
1858 * against quite old (pre-2.8, I think) headers only, not from more
1859 * recently compiled code.
1865 g_file_test (const gchar *filename,
1868 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
1871 if (utf8_filename == NULL)
1874 retval = g_file_test_utf8 (utf8_filename, test);
1876 g_free (utf8_filename);
1881 #undef g_file_get_contents
1884 g_file_get_contents (const gchar *filename,
1889 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
1892 if (utf8_filename == NULL)
1895 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
1897 g_free (utf8_filename);
1905 g_mkstemp (gchar *tmpl)
1909 static const char letters[] =
1910 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1911 static const int NLETTERS = sizeof (letters) - 1;
1914 static int counter = 0;
1916 /* find the last occurrence of 'XXXXXX' */
1917 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1925 /* Get some more or less random data. */
1926 g_get_current_time (&tv);
1927 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1929 for (count = 0; count < 100; value += 7777, ++count)
1933 /* Fill in the random bits. */
1934 XXXXXX[0] = letters[v % NLETTERS];
1936 XXXXXX[1] = letters[v % NLETTERS];
1938 XXXXXX[2] = letters[v % NLETTERS];
1940 XXXXXX[3] = letters[v % NLETTERS];
1942 XXXXXX[4] = letters[v % NLETTERS];
1944 XXXXXX[5] = letters[v % NLETTERS];
1946 /* This is the backward compatibility system codepage version,
1947 * thus use normal open().
1949 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1953 else if (errno != EEXIST)
1954 /* Any other error will apply also to other names we might
1955 * try, and there are 2^32 or so of them, so give up now.
1960 /* We got out of the loop because we ran out of combinations to try. */
1965 #undef g_file_open_tmp
1968 g_file_open_tmp (const gchar *tmpl,
1972 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1973 gchar *utf8_name_used;
1976 if (utf8_tmpl == NULL)
1979 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1985 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1987 g_free (utf8_name_used);
1994 #define __G_FILEUTILS_C__
1995 #include "galiasdef.c"