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));
968 /* If the final destination exists and is > 0 bytes, we want to sync the
969 * newly written file to ensure the data is on disk when we rename over
970 * the destination. Otherwise if we get a system crash we can lose both
971 * the new and the old file on some filesystems. (I.E. those that don't
972 * guarantee the data is written to the disk before the metadata.)
974 if (g_lstat (dest_file, &statbuf) == 0 &&
975 statbuf.st_size > 0 &&
976 fsync (fileno (file)) != 0)
982 g_file_error_from_errno (save_errno),
983 _("Failed to write file '%s': fsync() failed: %s"),
985 g_strerror (save_errno));
995 if (fclose (file) == EOF)
1001 g_file_error_from_errno (save_errno),
1002 _("Failed to close file '%s': fclose() failed: %s"),
1004 g_strerror (save_errno));
1006 g_unlink (tmp_name);
1011 retval = g_strdup (tmp_name);
1015 g_free (display_name);
1021 * g_file_set_contents:
1022 * @filename: name of a file to write @contents to, in the GLib file name
1024 * @contents: string to write to the file
1025 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1026 * @error: return location for a #GError, or %NULL
1028 * Writes all of @contents to a file named @filename, with good error checking.
1029 * If a file called @filename already exists it will be overwritten.
1031 * This write is atomic in the sense that it is first written to a temporary
1032 * file which is then renamed to the final name. Notes:
1035 * On Unix, if @filename already exists hard links to @filename will break.
1036 * Also since the file is recreated, existing permissions, access control
1037 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1038 * the link itself will be replaced, not the linked file.
1041 * On Windows renaming a file will not remove an existing file with the
1042 * new name, so on Windows there is a race condition between the existing
1043 * file being removed and the temporary file being renamed.
1046 * On Windows there is no way to remove a file that is open to some
1047 * process, or mapped into memory. Thus, this function will fail if
1048 * @filename already exists and is open.
1052 * If the call was sucessful, it returns %TRUE. If the call was not successful,
1053 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1054 * Possible error codes are those in the #GFileError enumeration.
1056 * Return value: %TRUE on success, %FALSE if an error occurred
1061 g_file_set_contents (const gchar *filename,
1062 const gchar *contents,
1066 gchar *tmp_filename;
1068 GError *rename_error = NULL;
1070 g_return_val_if_fail (filename != NULL, FALSE);
1071 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1072 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1073 g_return_val_if_fail (length >= -1, FALSE);
1076 length = strlen (contents);
1078 tmp_filename = write_to_temp_file (contents, length, filename, error);
1086 if (!rename_file (tmp_filename, filename, &rename_error))
1090 g_unlink (tmp_filename);
1091 g_propagate_error (error, rename_error);
1095 #else /* G_OS_WIN32 */
1097 /* Renaming failed, but on Windows this may just mean
1098 * the file already exists. So if the target file
1099 * exists, try deleting it and do the rename again.
1101 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1103 g_unlink (tmp_filename);
1104 g_propagate_error (error, rename_error);
1109 g_error_free (rename_error);
1111 if (g_unlink (filename) == -1)
1113 gchar *display_filename = g_filename_display_name (filename);
1115 int save_errno = errno;
1119 g_file_error_from_errno (save_errno),
1120 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1122 g_strerror (save_errno));
1124 g_free (display_filename);
1125 g_unlink (tmp_filename);
1130 if (!rename_file (tmp_filename, filename, error))
1132 g_unlink (tmp_filename);
1143 g_free (tmp_filename);
1148 * create_temp_file based on the mkstemp implementation from the GNU C library.
1149 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1152 create_temp_file (gchar *tmpl,
1157 static const char letters[] =
1158 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1159 static const int NLETTERS = sizeof (letters) - 1;
1162 static int counter = 0;
1164 /* find the last occurrence of "XXXXXX" */
1165 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1167 if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1173 /* Get some more or less random data. */
1174 g_get_current_time (&tv);
1175 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1177 for (count = 0; count < 100; value += 7777, ++count)
1181 /* Fill in the random bits. */
1182 XXXXXX[0] = letters[v % NLETTERS];
1184 XXXXXX[1] = letters[v % NLETTERS];
1186 XXXXXX[2] = letters[v % NLETTERS];
1188 XXXXXX[3] = letters[v % NLETTERS];
1190 XXXXXX[4] = letters[v % NLETTERS];
1192 XXXXXX[5] = letters[v % NLETTERS];
1194 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1195 fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, permissions);
1199 else if (errno != EEXIST)
1200 /* Any other error will apply also to other names we might
1201 * try, and there are 2^32 or so of them, so give up now.
1206 /* We got out of the loop because we ran out of combinations to try. */
1213 * @tmpl: template filename
1215 * Opens a temporary file. See the mkstemp() documentation
1216 * on most UNIX-like systems.
1218 * The parameter is a string that should follow the rules for
1219 * mkstemp() templates, i.e. contain the string "XXXXXX".
1220 * g_mkstemp() is slightly more flexible than mkstemp()
1221 * in that the sequence does not have to occur at the very end of the
1222 * template. The X string will
1223 * be modified to form the name of a file that didn't exist.
1224 * The string should be in the GLib file name encoding. Most importantly,
1225 * on Windows it should be in UTF-8.
1227 * Return value: A file handle (as from open()) to the file
1228 * opened for reading and writing. The file is opened in binary mode
1229 * on platforms where there is a difference. The file handle should be
1230 * closed with close(). In case of errors, -1 is returned.
1233 g_mkstemp (gchar *tmpl)
1235 return create_temp_file (tmpl, 0600);
1240 * @tmpl: Template for file name, as in g_mkstemp(), basename only,
1241 * or %NULL, to a default template
1242 * @name_used: location to store actual name used, or %NULL
1243 * @error: return location for a #GError
1245 * Opens a file for writing in the preferred directory for temporary
1246 * files (as returned by g_get_tmp_dir()).
1248 * @tmpl should be a string in the GLib file name encoding containing
1249 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1250 * However, unlike these functions, the template should only be a
1251 * basename, no directory components are allowed. If template is
1252 * %NULL, a default template is used.
1254 * Note that in contrast to g_mkstemp() (and mkstemp())
1255 * @tmpl is not modified, and might thus be a read-only literal string.
1257 * The actual name used is returned in @name_used if non-%NULL. This
1258 * string should be freed with g_free() when not needed any longer.
1259 * The returned name is in the GLib file name encoding.
1261 * Return value: A file handle (as from open()) to
1262 * the file opened for reading and writing. The file is opened in binary
1263 * mode on platforms where there is a difference. The file handle should be
1264 * closed with close(). In case of errors, -1 is returned
1265 * and @error will be set.
1268 g_file_open_tmp (const gchar *tmpl,
1281 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1283 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1287 gchar *display_tmpl = g_filename_display_name (tmpl);
1294 G_FILE_ERROR_FAILED,
1295 _("Template '%s' invalid, should not contain a '%s'"),
1297 g_free (display_tmpl);
1302 if (strstr (tmpl, "XXXXXX") == NULL)
1304 gchar *display_tmpl = g_filename_display_name (tmpl);
1307 G_FILE_ERROR_FAILED,
1308 _("Template '%s' doesn't contain XXXXXX"),
1310 g_free (display_tmpl);
1314 tmpdir = g_get_tmp_dir ();
1316 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1319 sep = G_DIR_SEPARATOR_S;
1321 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1323 retval = g_mkstemp (fulltemplate);
1327 int save_errno = errno;
1328 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1332 g_file_error_from_errno (save_errno),
1333 _("Failed to create file '%s': %s"),
1334 display_fulltemplate, g_strerror (save_errno));
1335 g_free (display_fulltemplate);
1336 g_free (fulltemplate);
1341 *name_used = fulltemplate;
1343 g_free (fulltemplate);
1349 g_build_path_va (const gchar *separator,
1350 const gchar *first_element,
1355 gint separator_len = strlen (separator);
1356 gboolean is_first = TRUE;
1357 gboolean have_leading = FALSE;
1358 const gchar *single_element = NULL;
1359 const gchar *next_element;
1360 const gchar *last_trailing = NULL;
1363 result = g_string_new (NULL);
1366 next_element = str_array[i++];
1368 next_element = first_element;
1372 const gchar *element;
1378 element = next_element;
1380 next_element = str_array[i++];
1382 next_element = va_arg (*args, gchar *);
1387 /* Ignore empty elements */
1396 strncmp (start, separator, separator_len) == 0)
1397 start += separator_len;
1400 end = start + strlen (start);
1404 while (end >= start + separator_len &&
1405 strncmp (end - separator_len, separator, separator_len) == 0)
1406 end -= separator_len;
1408 last_trailing = end;
1409 while (last_trailing >= element + separator_len &&
1410 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1411 last_trailing -= separator_len;
1415 /* If the leading and trailing separator strings are in the
1416 * same element and overlap, the result is exactly that element
1418 if (last_trailing <= start)
1419 single_element = element;
1421 g_string_append_len (result, element, start - element);
1422 have_leading = TRUE;
1425 single_element = NULL;
1432 g_string_append (result, separator);
1434 g_string_append_len (result, start, end - start);
1440 g_string_free (result, TRUE);
1441 return g_strdup (single_element);
1446 g_string_append (result, last_trailing);
1448 return g_string_free (result, FALSE);
1454 * @separator: a string used to separator the elements of the path.
1455 * @args: %NULL-terminated array of strings containing the path elements.
1457 * Behaves exactly like g_build_path(), but takes the path elements
1458 * as a string array, instead of varargs. This function is mainly
1459 * meant for language bindings.
1461 * Return value: a newly-allocated string that must be freed with g_free().
1466 g_build_pathv (const gchar *separator,
1472 return g_build_path_va (separator, NULL, NULL, args);
1478 * @separator: a string used to separator the elements of the path.
1479 * @first_element: the first element in the path
1480 * @Varargs: remaining elements in path, terminated by %NULL
1482 * Creates a path from a series of elements using @separator as the
1483 * separator between elements. At the boundary between two elements,
1484 * any trailing occurrences of separator in the first element, or
1485 * leading occurrences of separator in the second element are removed
1486 * and exactly one copy of the separator is inserted.
1488 * Empty elements are ignored.
1490 * The number of leading copies of the separator on the result is
1491 * the same as the number of leading copies of the separator on
1492 * the first non-empty element.
1494 * The number of trailing copies of the separator on the result is
1495 * the same as the number of trailing copies of the separator on
1496 * the last non-empty element. (Determination of the number of
1497 * trailing copies is done without stripping leading copies, so
1498 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1499 * has 1 trailing copy.)
1501 * However, if there is only a single non-empty element, and there
1502 * are no characters in that element not part of the leading or
1503 * trailing separators, then the result is exactly the original value
1506 * Other than for determination of the number of leading and trailing
1507 * copies of the separator, elements consisting only of copies
1508 * of the separator are ignored.
1510 * Return value: a newly-allocated string that must be freed with g_free().
1513 g_build_path (const gchar *separator,
1514 const gchar *first_element,
1520 g_return_val_if_fail (separator != NULL, NULL);
1522 va_start (args, first_element);
1523 str = g_build_path_va (separator, first_element, &args, NULL);
1532 g_build_pathname_va (const gchar *first_element,
1536 /* Code copied from g_build_pathv(), and modified to use two
1537 * alternative single-character separators.
1540 gboolean is_first = TRUE;
1541 gboolean have_leading = FALSE;
1542 const gchar *single_element = NULL;
1543 const gchar *next_element;
1544 const gchar *last_trailing = NULL;
1545 gchar current_separator = '\\';
1548 result = g_string_new (NULL);
1551 next_element = str_array[i++];
1553 next_element = first_element;
1557 const gchar *element;
1563 element = next_element;
1565 next_element = str_array[i++];
1567 next_element = va_arg (*args, gchar *);
1572 /* Ignore empty elements */
1581 (*start == '\\' || *start == '/'))
1583 current_separator = *start;
1588 end = start + strlen (start);
1592 while (end >= start + 1 &&
1593 (end[-1] == '\\' || end[-1] == '/'))
1595 current_separator = end[-1];
1599 last_trailing = end;
1600 while (last_trailing >= element + 1 &&
1601 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1606 /* If the leading and trailing separator strings are in the
1607 * same element and overlap, the result is exactly that element
1609 if (last_trailing <= start)
1610 single_element = element;
1612 g_string_append_len (result, element, start - element);
1613 have_leading = TRUE;
1616 single_element = NULL;
1623 g_string_append_len (result, ¤t_separator, 1);
1625 g_string_append_len (result, start, end - start);
1631 g_string_free (result, TRUE);
1632 return g_strdup (single_element);
1637 g_string_append (result, last_trailing);
1639 return g_string_free (result, FALSE);
1646 * g_build_filenamev:
1647 * @args: %NULL-terminated array of strings containing the path elements.
1649 * Behaves exactly like g_build_filename(), but takes the path elements
1650 * as a string array, instead of varargs. This function is mainly
1651 * meant for language bindings.
1653 * Return value: a newly-allocated string that must be freed with g_free().
1658 g_build_filenamev (gchar **args)
1663 str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1665 str = g_build_pathname_va (NULL, NULL, args);
1673 * @first_element: the first element in the path
1674 * @Varargs: remaining elements in path, terminated by %NULL
1676 * Creates a filename from a series of elements using the correct
1677 * separator for filenames.
1679 * On Unix, this function behaves identically to <literal>g_build_path
1680 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1682 * On Windows, it takes into account that either the backslash
1683 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1684 * as separator in filenames, but otherwise behaves as on Unix. When
1685 * file pathname separators need to be inserted, the one that last
1686 * previously occurred in the parameters (reading from left to right)
1689 * No attempt is made to force the resulting filename to be an absolute
1690 * path. If the first element is a relative path, the result will
1691 * be a relative path.
1693 * Return value: a newly-allocated string that must be freed with g_free().
1696 g_build_filename (const gchar *first_element,
1702 va_start (args, first_element);
1704 str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1706 str = g_build_pathname_va (first_element, &args, NULL);
1713 #define KILOBYTE_FACTOR 1024.0
1714 #define MEGABYTE_FACTOR (1024.0 * 1024.0)
1715 #define GIGABYTE_FACTOR (1024.0 * 1024.0 * 1024.0)
1718 * g_format_size_for_display:
1719 * @size: a size in bytes.
1721 * Formats a size (for example the size of a file) into a human readable string.
1722 * Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed
1723 * rounded to the nearest tenth. E.g. the file size 3292528 bytes will be
1724 * converted into the string "3.1 MB".
1726 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
1728 * This string should be freed with g_free() when not needed any longer.
1730 * Returns: a newly-allocated formatted string containing a human readable
1736 g_format_size_for_display (goffset size)
1738 if (size < (goffset) KILOBYTE_FACTOR)
1739 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
1742 gdouble displayed_size;
1744 if (size < (goffset) MEGABYTE_FACTOR)
1746 displayed_size = (gdouble) size / KILOBYTE_FACTOR;
1747 return g_strdup_printf (_("%.1f KB"), displayed_size);
1749 else if (size < (goffset) GIGABYTE_FACTOR)
1751 displayed_size = (gdouble) size / MEGABYTE_FACTOR;
1752 return g_strdup_printf (_("%.1f MB"), displayed_size);
1756 displayed_size = (gdouble) size / GIGABYTE_FACTOR;
1757 return g_strdup_printf (_("%.1f GB"), displayed_size);
1765 * @filename: the symbolic link
1766 * @error: return location for a #GError
1768 * Reads the contents of the symbolic link @filename like the POSIX
1769 * readlink() function. The returned string is in the encoding used
1770 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1772 * Returns: A newly-allocated string with the contents of the symbolic link,
1773 * or %NULL if an error occurred.
1778 g_file_read_link (const gchar *filename,
1781 #ifdef HAVE_READLINK
1787 buffer = g_malloc (size);
1791 read_size = readlink (filename, buffer, size);
1792 if (read_size < 0) {
1793 int save_errno = errno;
1794 gchar *display_filename = g_filename_display_name (filename);
1799 g_file_error_from_errno (save_errno),
1800 _("Failed to read the symbolic link '%s': %s"),
1802 g_strerror (save_errno));
1803 g_free (display_filename);
1808 if (read_size < size)
1810 buffer[read_size] = 0;
1815 buffer = g_realloc (buffer, size);
1818 g_set_error_literal (error,
1821 _("Symbolic links not supported"));
1827 /* NOTE : Keep this part last to ensure nothing in this file uses the
1828 * below binary compatibility versions.
1830 #if defined (G_OS_WIN32) && !defined (_WIN64)
1832 /* Binary compatibility versions. Will be called by code compiled
1833 * against quite old (pre-2.8, I think) headers only, not from more
1834 * recently compiled code.
1840 g_file_test (const gchar *filename,
1843 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
1846 if (utf8_filename == NULL)
1849 retval = g_file_test_utf8 (utf8_filename, test);
1851 g_free (utf8_filename);
1856 #undef g_file_get_contents
1859 g_file_get_contents (const gchar *filename,
1864 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
1867 if (utf8_filename == NULL)
1870 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
1872 g_free (utf8_filename);
1880 g_mkstemp (gchar *tmpl)
1884 static const char letters[] =
1885 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1886 static const int NLETTERS = sizeof (letters) - 1;
1889 static int counter = 0;
1891 /* find the last occurrence of 'XXXXXX' */
1892 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1900 /* Get some more or less random data. */
1901 g_get_current_time (&tv);
1902 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1904 for (count = 0; count < 100; value += 7777, ++count)
1908 /* Fill in the random bits. */
1909 XXXXXX[0] = letters[v % NLETTERS];
1911 XXXXXX[1] = letters[v % NLETTERS];
1913 XXXXXX[2] = letters[v % NLETTERS];
1915 XXXXXX[3] = letters[v % NLETTERS];
1917 XXXXXX[4] = letters[v % NLETTERS];
1919 XXXXXX[5] = letters[v % NLETTERS];
1921 /* This is the backward compatibility system codepage version,
1922 * thus use normal open().
1924 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1928 else if (errno != EEXIST)
1929 /* Any other error will apply also to other names we might
1930 * try, and there are 2^32 or so of them, so give up now.
1935 /* We got out of the loop because we ran out of combinations to try. */
1940 #undef g_file_open_tmp
1943 g_file_open_tmp (const gchar *tmpl,
1947 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1948 gchar *utf8_name_used;
1951 if (utf8_tmpl == NULL)
1954 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1960 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1962 g_free (utf8_name_used);
1969 #define __G_FILEUTILS_C__
1970 #include "galiasdef.c"