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)))
320 g_file_error_quark (void)
322 return g_quark_from_static_string ("g-file-error-quark");
326 * g_file_error_from_errno:
327 * @err_no: an "errno" value
329 * Gets a #GFileError constant based on the passed-in @errno.
330 * For example, if you pass in %EEXIST this function returns
331 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
332 * assume that all #GFileError values will exist.
334 * Normally a #GFileError value goes into a #GError returned
335 * from a function that manipulates files. So you would use
336 * g_file_error_from_errno() when constructing a #GError.
338 * Return value: #GFileError corresponding to the given @errno
341 g_file_error_from_errno (gint err_no)
347 return G_FILE_ERROR_EXIST;
353 return G_FILE_ERROR_ISDIR;
359 return G_FILE_ERROR_ACCES;
365 return G_FILE_ERROR_NAMETOOLONG;
371 return G_FILE_ERROR_NOENT;
377 return G_FILE_ERROR_NOTDIR;
383 return G_FILE_ERROR_NXIO;
389 return G_FILE_ERROR_NODEV;
395 return G_FILE_ERROR_ROFS;
401 return G_FILE_ERROR_TXTBSY;
407 return G_FILE_ERROR_FAULT;
413 return G_FILE_ERROR_LOOP;
419 return G_FILE_ERROR_NOSPC;
425 return G_FILE_ERROR_NOMEM;
431 return G_FILE_ERROR_MFILE;
437 return G_FILE_ERROR_NFILE;
443 return G_FILE_ERROR_BADF;
449 return G_FILE_ERROR_INVAL;
455 return G_FILE_ERROR_PIPE;
461 return G_FILE_ERROR_AGAIN;
467 return G_FILE_ERROR_INTR;
473 return G_FILE_ERROR_IO;
479 return G_FILE_ERROR_PERM;
485 return G_FILE_ERROR_NOSYS;
490 return G_FILE_ERROR_FAILED;
496 get_contents_stdio (const gchar *display_filename,
505 gsize total_bytes = 0;
506 gsize total_allocated = 0;
509 g_assert (f != NULL);
515 bytes = fread (buf, 1, sizeof (buf), f);
518 while ((total_bytes + bytes + 1) > total_allocated)
521 total_allocated *= 2;
523 total_allocated = MIN (bytes + 1, sizeof (buf));
525 tmp = g_try_realloc (str, total_allocated);
532 _("Could not allocate %lu bytes to read file \"%s\""),
533 (gulong) total_allocated,
546 g_file_error_from_errno (save_errno),
547 _("Error reading file '%s': %s"),
549 g_strerror (save_errno));
554 memcpy (str + total_bytes, buf, bytes);
556 if (total_bytes + bytes < total_bytes)
561 _("File \"%s\" is too large"),
567 total_bytes += bytes;
572 if (total_allocated == 0)
574 str = g_new (gchar, 1);
578 str[total_bytes] = '\0';
581 *length = total_bytes;
598 get_contents_regfile (const gchar *display_filename,
599 struct stat *stat_buf,
610 size = stat_buf->st_size;
612 alloc_size = size + 1;
613 buf = g_try_malloc (alloc_size);
620 _("Could not allocate %lu bytes to read file \"%s\""),
628 while (bytes_read < size)
632 rc = read (fd, buf + bytes_read, size - bytes_read);
638 int save_errno = errno;
643 g_file_error_from_errno (save_errno),
644 _("Failed to read from file '%s': %s"),
646 g_strerror (save_errno));
657 buf[bytes_read] = '\0';
660 *length = bytes_read;
676 get_contents_posix (const gchar *filename,
681 struct stat stat_buf;
683 gchar *display_filename = g_filename_display_name (filename);
685 /* O_BINARY useful on Cygwin */
686 fd = open (filename, O_RDONLY|O_BINARY);
690 int save_errno = errno;
694 g_file_error_from_errno (save_errno),
695 _("Failed to open file '%s': %s"),
697 g_strerror (save_errno));
698 g_free (display_filename);
703 /* I don't think this will ever fail, aside from ENOMEM, but. */
704 if (fstat (fd, &stat_buf) < 0)
706 int save_errno = errno;
711 g_file_error_from_errno (save_errno),
712 _("Failed to get attributes of file '%s': fstat() failed: %s"),
714 g_strerror (save_errno));
715 g_free (display_filename);
720 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
722 gboolean retval = get_contents_regfile (display_filename,
728 g_free (display_filename);
737 f = fdopen (fd, "r");
741 int save_errno = errno;
745 g_file_error_from_errno (save_errno),
746 _("Failed to open file '%s': fdopen() failed: %s"),
748 g_strerror (save_errno));
749 g_free (display_filename);
754 retval = get_contents_stdio (display_filename, f, contents, length, error);
755 g_free (display_filename);
761 #else /* G_OS_WIN32 */
764 get_contents_win32 (const gchar *filename,
771 gchar *display_filename = g_filename_display_name (filename);
774 f = g_fopen (filename, "rb");
781 g_file_error_from_errno (save_errno),
782 _("Failed to open file '%s': %s"),
784 g_strerror (save_errno));
785 g_free (display_filename);
790 retval = get_contents_stdio (display_filename, f, contents, length, error);
791 g_free (display_filename);
799 * g_file_get_contents:
800 * @filename: name of a file to read contents from, in the GLib file name encoding
801 * @contents: location to store an allocated string, use g_free() to free
802 * the returned string
803 * @length: location to store length in bytes of the contents, or %NULL
804 * @error: return location for a #GError, or %NULL
806 * Reads an entire file into allocated memory, with good error
809 * If the call was successful, it returns %TRUE and sets @contents to the file
810 * contents and @length to the length of the file contents in bytes. The string
811 * stored in @contents will be nul-terminated, so for text files you can pass
812 * %NULL for the @length argument. If the call was not successful, it returns
813 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
814 * codes are those in the #GFileError enumeration. In the error case,
815 * @contents is set to %NULL and @length is set to zero.
817 * Return value: %TRUE on success, %FALSE if an error occurred
820 g_file_get_contents (const gchar *filename,
825 g_return_val_if_fail (filename != NULL, FALSE);
826 g_return_val_if_fail (contents != NULL, FALSE);
833 return get_contents_win32 (filename, contents, length, error);
835 return get_contents_posix (filename, contents, length, error);
840 rename_file (const char *old_name,
841 const char *new_name,
845 if (g_rename (old_name, new_name) == -1)
847 int save_errno = errno;
848 gchar *display_old_name = g_filename_display_name (old_name);
849 gchar *display_new_name = g_filename_display_name (new_name);
853 g_file_error_from_errno (save_errno),
854 _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
857 g_strerror (save_errno));
859 g_free (display_old_name);
860 g_free (display_new_name);
869 write_to_temp_file (const gchar *contents,
871 const gchar *dest_file,
883 tmp_name = g_strdup_printf ("%s.XXXXXX", dest_file);
886 fd = create_temp_file (tmp_name, 0666);
889 display_name = g_filename_display_name (tmp_name);
895 g_file_error_from_errno (save_errno),
896 _("Failed to create file '%s': %s"),
897 display_name, g_strerror (save_errno));
903 file = fdopen (fd, "wb");
909 g_file_error_from_errno (save_errno),
910 _("Failed to open file '%s' for writing: fdopen() failed: %s"),
912 g_strerror (save_errno));
926 n_written = fwrite (contents, 1, length, file);
928 if (n_written < length)
934 g_file_error_from_errno (save_errno),
935 _("Failed to write file '%s': fwrite() failed: %s"),
937 g_strerror (save_errno));
947 if (fflush (file) != 0)
953 g_file_error_from_errno (save_errno),
954 _("Failed to write file '%s': fflush() failed: %s"),
956 g_strerror (save_errno));
965 /* If the final destination exists, we want to sync the newly written
966 * file to ensure the data is on disk when we rename over the destination.
967 * otherwise if we get a system crash we can lose both the new and the
968 * old file on some filesystems. (I.E. those that don't guarantee the
969 * data is written to the disk before the metadata.)
971 if (g_file_test (dest_file, G_FILE_TEST_EXISTS) &&
972 fsync (fileno (file)) != 0)
978 g_file_error_from_errno (save_errno),
979 _("Failed to write file '%s': fsync() failed: %s"),
981 g_strerror (save_errno));
990 if (fclose (file) == EOF)
996 g_file_error_from_errno (save_errno),
997 _("Failed to close file '%s': fclose() failed: %s"),
999 g_strerror (save_errno));
1001 g_unlink (tmp_name);
1006 retval = g_strdup (tmp_name);
1010 g_free (display_name);
1016 * g_file_set_contents:
1017 * @filename: name of a file to write @contents to, in the GLib file name
1019 * @contents: string to write to the file
1020 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1021 * @error: return location for a #GError, or %NULL
1023 * Writes all of @contents to a file named @filename, with good error checking.
1024 * If a file called @filename already exists it will be overwritten.
1026 * This write is atomic in the sense that it is first written to a temporary
1027 * file which is then renamed to the final name. Notes:
1030 * On Unix, if @filename already exists hard links to @filename will break.
1031 * Also since the file is recreated, existing permissions, access control
1032 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1033 * the link itself will be replaced, not the linked file.
1036 * On Windows renaming a file will not remove an existing file with the
1037 * new name, so on Windows there is a race condition between the existing
1038 * file being removed and the temporary file being renamed.
1041 * On Windows there is no way to remove a file that is open to some
1042 * process, or mapped into memory. Thus, this function will fail if
1043 * @filename already exists and is open.
1047 * If the call was sucessful, it returns %TRUE. If the call was not successful,
1048 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1049 * Possible error codes are those in the #GFileError enumeration.
1051 * Return value: %TRUE on success, %FALSE if an error occurred
1056 g_file_set_contents (const gchar *filename,
1057 const gchar *contents,
1061 gchar *tmp_filename;
1063 GError *rename_error = NULL;
1065 g_return_val_if_fail (filename != NULL, FALSE);
1066 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1067 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1068 g_return_val_if_fail (length >= -1, FALSE);
1071 length = strlen (contents);
1073 tmp_filename = write_to_temp_file (contents, length, filename, error);
1081 if (!rename_file (tmp_filename, filename, &rename_error))
1085 g_unlink (tmp_filename);
1086 g_propagate_error (error, rename_error);
1090 #else /* G_OS_WIN32 */
1092 /* Renaming failed, but on Windows this may just mean
1093 * the file already exists. So if the target file
1094 * exists, try deleting it and do the rename again.
1096 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1098 g_unlink (tmp_filename);
1099 g_propagate_error (error, rename_error);
1104 g_error_free (rename_error);
1106 if (g_unlink (filename) == -1)
1108 gchar *display_filename = g_filename_display_name (filename);
1110 int save_errno = errno;
1114 g_file_error_from_errno (save_errno),
1115 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1117 g_strerror (save_errno));
1119 g_free (display_filename);
1120 g_unlink (tmp_filename);
1125 if (!rename_file (tmp_filename, filename, error))
1127 g_unlink (tmp_filename);
1138 g_free (tmp_filename);
1143 * create_temp_file based on the mkstemp implementation from the GNU C library.
1144 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1147 create_temp_file (gchar *tmpl,
1152 static const char letters[] =
1153 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1154 static const int NLETTERS = sizeof (letters) - 1;
1157 static int counter = 0;
1159 /* find the last occurrence of "XXXXXX" */
1160 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1162 if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1168 /* Get some more or less random data. */
1169 g_get_current_time (&tv);
1170 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1172 for (count = 0; count < 100; value += 7777, ++count)
1176 /* Fill in the random bits. */
1177 XXXXXX[0] = letters[v % NLETTERS];
1179 XXXXXX[1] = letters[v % NLETTERS];
1181 XXXXXX[2] = letters[v % NLETTERS];
1183 XXXXXX[3] = letters[v % NLETTERS];
1185 XXXXXX[4] = letters[v % NLETTERS];
1187 XXXXXX[5] = letters[v % NLETTERS];
1189 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1190 fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, permissions);
1194 else if (errno != EEXIST)
1195 /* Any other error will apply also to other names we might
1196 * try, and there are 2^32 or so of them, so give up now.
1201 /* We got out of the loop because we ran out of combinations to try. */
1208 * @tmpl: template filename
1210 * Opens a temporary file. See the mkstemp() documentation
1211 * on most UNIX-like systems.
1213 * The parameter is a string that should follow the rules for
1214 * mkstemp() templates, i.e. contain the string "XXXXXX".
1215 * g_mkstemp() is slightly more flexible than mkstemp()
1216 * in that the sequence does not have to occur at the very end of the
1217 * template. The X string will
1218 * be modified to form the name of a file that didn't exist.
1219 * The string should be in the GLib file name encoding. Most importantly,
1220 * on Windows it should be in UTF-8.
1222 * Return value: A file handle (as from open()) to the file
1223 * opened for reading and writing. The file is opened in binary mode
1224 * on platforms where there is a difference. The file handle should be
1225 * closed with close(). In case of errors, -1 is returned.
1228 g_mkstemp (gchar *tmpl)
1230 return create_temp_file (tmpl, 0600);
1235 * @tmpl: Template for file name, as in g_mkstemp(), basename only,
1236 * or %NULL, to a default template
1237 * @name_used: location to store actual name used, or %NULL
1238 * @error: return location for a #GError
1240 * Opens a file for writing in the preferred directory for temporary
1241 * files (as returned by g_get_tmp_dir()).
1243 * @tmpl should be a string in the GLib file name encoding containing
1244 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1245 * However, unlike these functions, the template should only be a
1246 * basename, no directory components are allowed. If template is
1247 * %NULL, a default template is used.
1249 * Note that in contrast to g_mkstemp() (and mkstemp())
1250 * @tmpl is not modified, and might thus be a read-only literal string.
1252 * The actual name used is returned in @name_used if non-%NULL. This
1253 * string should be freed with g_free() when not needed any longer.
1254 * The returned name is in the GLib file name encoding.
1256 * Return value: A file handle (as from open()) to
1257 * the file opened for reading and writing. The file is opened in binary
1258 * mode on platforms where there is a difference. The file handle should be
1259 * closed with close(). In case of errors, -1 is returned
1260 * and @error will be set.
1263 g_file_open_tmp (const gchar *tmpl,
1276 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1278 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1282 gchar *display_tmpl = g_filename_display_name (tmpl);
1289 G_FILE_ERROR_FAILED,
1290 _("Template '%s' invalid, should not contain a '%s'"),
1292 g_free (display_tmpl);
1297 if (strstr (tmpl, "XXXXXX") == NULL)
1299 gchar *display_tmpl = g_filename_display_name (tmpl);
1302 G_FILE_ERROR_FAILED,
1303 _("Template '%s' doesn't contain XXXXXX"),
1305 g_free (display_tmpl);
1309 tmpdir = g_get_tmp_dir ();
1311 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1314 sep = G_DIR_SEPARATOR_S;
1316 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1318 retval = g_mkstemp (fulltemplate);
1322 int save_errno = errno;
1323 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1327 g_file_error_from_errno (save_errno),
1328 _("Failed to create file '%s': %s"),
1329 display_fulltemplate, g_strerror (save_errno));
1330 g_free (display_fulltemplate);
1331 g_free (fulltemplate);
1336 *name_used = fulltemplate;
1338 g_free (fulltemplate);
1344 g_build_path_va (const gchar *separator,
1345 const gchar *first_element,
1350 gint separator_len = strlen (separator);
1351 gboolean is_first = TRUE;
1352 gboolean have_leading = FALSE;
1353 const gchar *single_element = NULL;
1354 const gchar *next_element;
1355 const gchar *last_trailing = NULL;
1358 result = g_string_new (NULL);
1361 next_element = str_array[i++];
1363 next_element = first_element;
1367 const gchar *element;
1373 element = next_element;
1375 next_element = str_array[i++];
1377 next_element = va_arg (*args, gchar *);
1382 /* Ignore empty elements */
1391 strncmp (start, separator, separator_len) == 0)
1392 start += separator_len;
1395 end = start + strlen (start);
1399 while (end >= start + separator_len &&
1400 strncmp (end - separator_len, separator, separator_len) == 0)
1401 end -= separator_len;
1403 last_trailing = end;
1404 while (last_trailing >= element + separator_len &&
1405 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1406 last_trailing -= separator_len;
1410 /* If the leading and trailing separator strings are in the
1411 * same element and overlap, the result is exactly that element
1413 if (last_trailing <= start)
1414 single_element = element;
1416 g_string_append_len (result, element, start - element);
1417 have_leading = TRUE;
1420 single_element = NULL;
1427 g_string_append (result, separator);
1429 g_string_append_len (result, start, end - start);
1435 g_string_free (result, TRUE);
1436 return g_strdup (single_element);
1441 g_string_append (result, last_trailing);
1443 return g_string_free (result, FALSE);
1449 * @separator: a string used to separator the elements of the path.
1450 * @args: %NULL-terminated array of strings containing the path elements.
1452 * Behaves exactly like g_build_path(), but takes the path elements
1453 * as a string array, instead of varargs. This function is mainly
1454 * meant for language bindings.
1456 * Return value: a newly-allocated string that must be freed with g_free().
1461 g_build_pathv (const gchar *separator,
1467 return g_build_path_va (separator, NULL, NULL, args);
1473 * @separator: a string used to separator the elements of the path.
1474 * @first_element: the first element in the path
1475 * @Varargs: remaining elements in path, terminated by %NULL
1477 * Creates a path from a series of elements using @separator as the
1478 * separator between elements. At the boundary between two elements,
1479 * any trailing occurrences of separator in the first element, or
1480 * leading occurrences of separator in the second element are removed
1481 * and exactly one copy of the separator is inserted.
1483 * Empty elements are ignored.
1485 * The number of leading copies of the separator on the result is
1486 * the same as the number of leading copies of the separator on
1487 * the first non-empty element.
1489 * The number of trailing copies of the separator on the result is
1490 * the same as the number of trailing copies of the separator on
1491 * the last non-empty element. (Determination of the number of
1492 * trailing copies is done without stripping leading copies, so
1493 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1494 * has 1 trailing copy.)
1496 * However, if there is only a single non-empty element, and there
1497 * are no characters in that element not part of the leading or
1498 * trailing separators, then the result is exactly the original value
1501 * Other than for determination of the number of leading and trailing
1502 * copies of the separator, elements consisting only of copies
1503 * of the separator are ignored.
1505 * Return value: a newly-allocated string that must be freed with g_free().
1508 g_build_path (const gchar *separator,
1509 const gchar *first_element,
1515 g_return_val_if_fail (separator != NULL, NULL);
1517 va_start (args, first_element);
1518 str = g_build_path_va (separator, first_element, &args, NULL);
1527 g_build_pathname_va (const gchar *first_element,
1531 /* Code copied from g_build_pathv(), and modified to use two
1532 * alternative single-character separators.
1535 gboolean is_first = TRUE;
1536 gboolean have_leading = FALSE;
1537 const gchar *single_element = NULL;
1538 const gchar *next_element;
1539 const gchar *last_trailing = NULL;
1540 gchar current_separator = '\\';
1543 result = g_string_new (NULL);
1546 next_element = str_array[i++];
1548 next_element = first_element;
1552 const gchar *element;
1558 element = next_element;
1560 next_element = str_array[i++];
1562 next_element = va_arg (*args, gchar *);
1567 /* Ignore empty elements */
1576 (*start == '\\' || *start == '/'))
1578 current_separator = *start;
1583 end = start + strlen (start);
1587 while (end >= start + 1 &&
1588 (end[-1] == '\\' || end[-1] == '/'))
1590 current_separator = end[-1];
1594 last_trailing = end;
1595 while (last_trailing >= element + 1 &&
1596 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1601 /* If the leading and trailing separator strings are in the
1602 * same element and overlap, the result is exactly that element
1604 if (last_trailing <= start)
1605 single_element = element;
1607 g_string_append_len (result, element, start - element);
1608 have_leading = TRUE;
1611 single_element = NULL;
1618 g_string_append_len (result, ¤t_separator, 1);
1620 g_string_append_len (result, start, end - start);
1626 g_string_free (result, TRUE);
1627 return g_strdup (single_element);
1632 g_string_append (result, last_trailing);
1634 return g_string_free (result, FALSE);
1641 * g_build_filenamev:
1642 * @args: %NULL-terminated array of strings containing the path elements.
1644 * Behaves exactly like g_build_filename(), but takes the path elements
1645 * as a string array, instead of varargs. This function is mainly
1646 * meant for language bindings.
1648 * Return value: a newly-allocated string that must be freed with g_free().
1653 g_build_filenamev (gchar **args)
1658 str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1660 str = g_build_pathname_va (NULL, NULL, args);
1668 * @first_element: the first element in the path
1669 * @Varargs: remaining elements in path, terminated by %NULL
1671 * Creates a filename from a series of elements using the correct
1672 * separator for filenames.
1674 * On Unix, this function behaves identically to <literal>g_build_path
1675 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1677 * On Windows, it takes into account that either the backslash
1678 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1679 * as separator in filenames, but otherwise behaves as on Unix. When
1680 * file pathname separators need to be inserted, the one that last
1681 * previously occurred in the parameters (reading from left to right)
1684 * No attempt is made to force the resulting filename to be an absolute
1685 * path. If the first element is a relative path, the result will
1686 * be a relative path.
1688 * Return value: a newly-allocated string that must be freed with g_free().
1691 g_build_filename (const gchar *first_element,
1697 va_start (args, first_element);
1699 str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1701 str = g_build_pathname_va (first_element, &args, NULL);
1708 #define KILOBYTE_FACTOR 1024.0
1709 #define MEGABYTE_FACTOR (1024.0 * 1024.0)
1710 #define GIGABYTE_FACTOR (1024.0 * 1024.0 * 1024.0)
1713 * g_format_size_for_display:
1714 * @size: a size in bytes.
1716 * Formats a size (for example the size of a file) into a human readable string.
1717 * Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed
1718 * rounded to the nearest tenth. E.g. the file size 3292528 bytes will be
1719 * converted into the string "3.1 MB".
1721 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
1723 * This string should be freed with g_free() when not needed any longer.
1725 * Returns: a newly-allocated formatted string containing a human readable
1731 g_format_size_for_display (goffset size)
1733 if (size < (goffset) KILOBYTE_FACTOR)
1734 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
1737 gdouble displayed_size;
1739 if (size < (goffset) MEGABYTE_FACTOR)
1741 displayed_size = (gdouble) size / KILOBYTE_FACTOR;
1742 return g_strdup_printf (_("%.1f KB"), displayed_size);
1744 else if (size < (goffset) GIGABYTE_FACTOR)
1746 displayed_size = (gdouble) size / MEGABYTE_FACTOR;
1747 return g_strdup_printf (_("%.1f MB"), displayed_size);
1751 displayed_size = (gdouble) size / GIGABYTE_FACTOR;
1752 return g_strdup_printf (_("%.1f GB"), displayed_size);
1760 * @filename: the symbolic link
1761 * @error: return location for a #GError
1763 * Reads the contents of the symbolic link @filename like the POSIX
1764 * readlink() function. The returned string is in the encoding used
1765 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1767 * Returns: A newly-allocated string with the contents of the symbolic link,
1768 * or %NULL if an error occurred.
1773 g_file_read_link (const gchar *filename,
1776 #ifdef HAVE_READLINK
1782 buffer = g_malloc (size);
1786 read_size = readlink (filename, buffer, size);
1787 if (read_size < 0) {
1788 int save_errno = errno;
1789 gchar *display_filename = g_filename_display_name (filename);
1794 g_file_error_from_errno (save_errno),
1795 _("Failed to read the symbolic link '%s': %s"),
1797 g_strerror (save_errno));
1798 g_free (display_filename);
1803 if (read_size < size)
1805 buffer[read_size] = 0;
1810 buffer = g_realloc (buffer, size);
1813 g_set_error_literal (error,
1816 _("Symbolic links not supported"));
1822 /* NOTE : Keep this part last to ensure nothing in this file uses the
1823 * below binary compatibility versions.
1825 #if defined (G_OS_WIN32) && !defined (_WIN64)
1827 /* Binary compatibility versions. Will be called by code compiled
1828 * against quite old (pre-2.8, I think) headers only, not from more
1829 * recently compiled code.
1835 g_file_test (const gchar *filename,
1838 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
1841 if (utf8_filename == NULL)
1844 retval = g_file_test_utf8 (utf8_filename, test);
1846 g_free (utf8_filename);
1851 #undef g_file_get_contents
1854 g_file_get_contents (const gchar *filename,
1859 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
1862 if (utf8_filename == NULL)
1865 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
1867 g_free (utf8_filename);
1875 g_mkstemp (gchar *tmpl)
1879 static const char letters[] =
1880 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1881 static const int NLETTERS = sizeof (letters) - 1;
1884 static int counter = 0;
1886 /* find the last occurrence of 'XXXXXX' */
1887 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1895 /* Get some more or less random data. */
1896 g_get_current_time (&tv);
1897 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1899 for (count = 0; count < 100; value += 7777, ++count)
1903 /* Fill in the random bits. */
1904 XXXXXX[0] = letters[v % NLETTERS];
1906 XXXXXX[1] = letters[v % NLETTERS];
1908 XXXXXX[2] = letters[v % NLETTERS];
1910 XXXXXX[3] = letters[v % NLETTERS];
1912 XXXXXX[4] = letters[v % NLETTERS];
1914 XXXXXX[5] = letters[v % NLETTERS];
1916 /* This is the backward compatibility system codepage version,
1917 * thus use normal open().
1919 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1923 else if (errno != EEXIST)
1924 /* Any other error will apply also to other names we might
1925 * try, and there are 2^32 or so of them, so give up now.
1930 /* We got out of the loop because we ran out of combinations to try. */
1935 #undef g_file_open_tmp
1938 g_file_open_tmp (const gchar *tmpl,
1942 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1943 gchar *utf8_name_used;
1946 if (utf8_tmpl == NULL)
1949 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1955 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1957 g_free (utf8_name_used);
1964 #define __G_FILEUTILS_C__
1965 #include "galiasdef.c"