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 *template,
883 tmp_name = g_strdup_printf ("%s.XXXXXX", template);
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 (fclose (file) == EOF)
953 g_file_error_from_errno (save_errno),
954 _("Failed to close file '%s': fclose() failed: %s"),
956 g_strerror (save_errno));
963 retval = g_strdup (tmp_name);
967 g_free (display_name);
973 * g_file_set_contents:
974 * @filename: name of a file to write @contents to, in the GLib file name
976 * @contents: string to write to the file
977 * @length: length of @contents, or -1 if @contents is a nul-terminated string
978 * @error: return location for a #GError, or %NULL
980 * Writes all of @contents to a file named @filename, with good error checking.
981 * If a file called @filename already exists it will be overwritten.
983 * This write is atomic in the sense that it is first written to a temporary
984 * file which is then renamed to the final name. Notes:
987 * On Unix, if @filename already exists hard links to @filename will break.
988 * Also since the file is recreated, existing permissions, access control
989 * lists, metadata etc. may be lost. If @filename is a symbolic link,
990 * the link itself will be replaced, not the linked file.
993 * On Windows renaming a file will not remove an existing file with the
994 * new name, so on Windows there is a race condition between the existing
995 * file being removed and the temporary file being renamed.
998 * On Windows there is no way to remove a file that is open to some
999 * process, or mapped into memory. Thus, this function will fail if
1000 * @filename already exists and is open.
1004 * If the call was sucessful, it returns %TRUE. If the call was not successful,
1005 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1006 * Possible error codes are those in the #GFileError enumeration.
1008 * Return value: %TRUE on success, %FALSE if an error occurred
1013 g_file_set_contents (const gchar *filename,
1014 const gchar *contents,
1018 gchar *tmp_filename;
1020 GError *rename_error = NULL;
1022 g_return_val_if_fail (filename != NULL, FALSE);
1023 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1024 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1025 g_return_val_if_fail (length >= -1, FALSE);
1028 length = strlen (contents);
1030 tmp_filename = write_to_temp_file (contents, length, filename, error);
1038 if (!rename_file (tmp_filename, filename, &rename_error))
1042 g_unlink (tmp_filename);
1043 g_propagate_error (error, rename_error);
1047 #else /* G_OS_WIN32 */
1049 /* Renaming failed, but on Windows this may just mean
1050 * the file already exists. So if the target file
1051 * exists, try deleting it and do the rename again.
1053 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1055 g_unlink (tmp_filename);
1056 g_propagate_error (error, rename_error);
1061 g_error_free (rename_error);
1063 if (g_unlink (filename) == -1)
1065 gchar *display_filename = g_filename_display_name (filename);
1067 int save_errno = errno;
1071 g_file_error_from_errno (save_errno),
1072 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1074 g_strerror (save_errno));
1076 g_free (display_filename);
1077 g_unlink (tmp_filename);
1082 if (!rename_file (tmp_filename, filename, error))
1084 g_unlink (tmp_filename);
1095 g_free (tmp_filename);
1100 * create_temp_file based on the mkstemp implementation from the GNU C library.
1101 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1104 create_temp_file (gchar *tmpl,
1109 static const char letters[] =
1110 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1111 static const int NLETTERS = sizeof (letters) - 1;
1114 static int counter = 0;
1116 /* find the last occurrence of "XXXXXX" */
1117 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1119 if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1125 /* Get some more or less random data. */
1126 g_get_current_time (&tv);
1127 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1129 for (count = 0; count < 100; value += 7777, ++count)
1133 /* Fill in the random bits. */
1134 XXXXXX[0] = letters[v % NLETTERS];
1136 XXXXXX[1] = letters[v % NLETTERS];
1138 XXXXXX[2] = letters[v % NLETTERS];
1140 XXXXXX[3] = letters[v % NLETTERS];
1142 XXXXXX[4] = letters[v % NLETTERS];
1144 XXXXXX[5] = letters[v % NLETTERS];
1146 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1147 fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, permissions);
1151 else if (errno != EEXIST)
1152 /* Any other error will apply also to other names we might
1153 * try, and there are 2^32 or so of them, so give up now.
1158 /* We got out of the loop because we ran out of combinations to try. */
1165 * @tmpl: template filename
1167 * Opens a temporary file. See the mkstemp() documentation
1168 * on most UNIX-like systems.
1170 * The parameter is a string that should follow the rules for
1171 * mkstemp() templates, i.e. contain the string "XXXXXX".
1172 * g_mkstemp() is slightly more flexible than mkstemp()
1173 * in that the sequence does not have to occur at the very end of the
1174 * template. The X string will
1175 * be modified to form the name of a file that didn't exist.
1176 * The string should be in the GLib file name encoding. Most importantly,
1177 * on Windows it should be in UTF-8.
1179 * Return value: A file handle (as from open()) to the file
1180 * opened for reading and writing. The file is opened in binary mode
1181 * on platforms where there is a difference. The file handle should be
1182 * closed with close(). In case of errors, -1 is returned.
1185 g_mkstemp (gchar *tmpl)
1187 return create_temp_file (tmpl, 0600);
1192 * @tmpl: Template for file name, as in g_mkstemp(), basename only,
1193 * or %NULL, to a default template
1194 * @name_used: location to store actual name used, or %NULL
1195 * @error: return location for a #GError
1197 * Opens a file for writing in the preferred directory for temporary
1198 * files (as returned by g_get_tmp_dir()).
1200 * @tmpl should be a string in the GLib file name encoding containing
1201 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1202 * However, unlike these functions, the template should only be a
1203 * basename, no directory components are allowed. If template is
1204 * %NULL, a default template is used.
1206 * Note that in contrast to g_mkstemp() (and mkstemp())
1207 * @tmpl is not modified, and might thus be a read-only literal string.
1209 * The actual name used is returned in @name_used if non-%NULL. This
1210 * string should be freed with g_free() when not needed any longer.
1211 * The returned name is in the GLib file name encoding.
1213 * Return value: A file handle (as from open()) to
1214 * the file opened for reading and writing. The file is opened in binary
1215 * mode on platforms where there is a difference. The file handle should be
1216 * closed with close(). In case of errors, -1 is returned
1217 * and @error will be set.
1220 g_file_open_tmp (const gchar *tmpl,
1233 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1235 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1239 gchar *display_tmpl = g_filename_display_name (tmpl);
1246 G_FILE_ERROR_FAILED,
1247 _("Template '%s' invalid, should not contain a '%s'"),
1249 g_free (display_tmpl);
1254 if (strstr (tmpl, "XXXXXX") == NULL)
1256 gchar *display_tmpl = g_filename_display_name (tmpl);
1259 G_FILE_ERROR_FAILED,
1260 _("Template '%s' doesn't contain XXXXXX"),
1262 g_free (display_tmpl);
1266 tmpdir = g_get_tmp_dir ();
1268 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1271 sep = G_DIR_SEPARATOR_S;
1273 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1275 retval = g_mkstemp (fulltemplate);
1279 int save_errno = errno;
1280 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1284 g_file_error_from_errno (save_errno),
1285 _("Failed to create file '%s': %s"),
1286 display_fulltemplate, g_strerror (save_errno));
1287 g_free (display_fulltemplate);
1288 g_free (fulltemplate);
1293 *name_used = fulltemplate;
1295 g_free (fulltemplate);
1301 g_build_path_va (const gchar *separator,
1302 const gchar *first_element,
1307 gint separator_len = strlen (separator);
1308 gboolean is_first = TRUE;
1309 gboolean have_leading = FALSE;
1310 const gchar *single_element = NULL;
1311 const gchar *next_element;
1312 const gchar *last_trailing = NULL;
1315 result = g_string_new (NULL);
1318 next_element = str_array[i++];
1320 next_element = first_element;
1324 const gchar *element;
1330 element = next_element;
1332 next_element = str_array[i++];
1334 next_element = va_arg (*args, gchar *);
1339 /* Ignore empty elements */
1348 strncmp (start, separator, separator_len) == 0)
1349 start += separator_len;
1352 end = start + strlen (start);
1356 while (end >= start + separator_len &&
1357 strncmp (end - separator_len, separator, separator_len) == 0)
1358 end -= separator_len;
1360 last_trailing = end;
1361 while (last_trailing >= element + separator_len &&
1362 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1363 last_trailing -= separator_len;
1367 /* If the leading and trailing separator strings are in the
1368 * same element and overlap, the result is exactly that element
1370 if (last_trailing <= start)
1371 single_element = element;
1373 g_string_append_len (result, element, start - element);
1374 have_leading = TRUE;
1377 single_element = NULL;
1384 g_string_append (result, separator);
1386 g_string_append_len (result, start, end - start);
1392 g_string_free (result, TRUE);
1393 return g_strdup (single_element);
1398 g_string_append (result, last_trailing);
1400 return g_string_free (result, FALSE);
1406 * @separator: a string used to separator the elements of the path.
1407 * @args: %NULL-terminated array of strings containing the path elements.
1409 * Behaves exactly like g_build_path(), but takes the path elements
1410 * as a string array, instead of varargs. This function is mainly
1411 * meant for language bindings.
1413 * Return value: a newly-allocated string that must be freed with g_free().
1418 g_build_pathv (const gchar *separator,
1424 return g_build_path_va (separator, NULL, NULL, args);
1430 * @separator: a string used to separator the elements of the path.
1431 * @first_element: the first element in the path
1432 * @Varargs: remaining elements in path, terminated by %NULL
1434 * Creates a path from a series of elements using @separator as the
1435 * separator between elements. At the boundary between two elements,
1436 * any trailing occurrences of separator in the first element, or
1437 * leading occurrences of separator in the second element are removed
1438 * and exactly one copy of the separator is inserted.
1440 * Empty elements are ignored.
1442 * The number of leading copies of the separator on the result is
1443 * the same as the number of leading copies of the separator on
1444 * the first non-empty element.
1446 * The number of trailing copies of the separator on the result is
1447 * the same as the number of trailing copies of the separator on
1448 * the last non-empty element. (Determination of the number of
1449 * trailing copies is done without stripping leading copies, so
1450 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1451 * has 1 trailing copy.)
1453 * However, if there is only a single non-empty element, and there
1454 * are no characters in that element not part of the leading or
1455 * trailing separators, then the result is exactly the original value
1458 * Other than for determination of the number of leading and trailing
1459 * copies of the separator, elements consisting only of copies
1460 * of the separator are ignored.
1462 * Return value: a newly-allocated string that must be freed with g_free().
1465 g_build_path (const gchar *separator,
1466 const gchar *first_element,
1472 g_return_val_if_fail (separator != NULL, NULL);
1474 va_start (args, first_element);
1475 str = g_build_path_va (separator, first_element, &args, NULL);
1484 g_build_pathname_va (const gchar *first_element,
1488 /* Code copied from g_build_pathv(), and modified to use two
1489 * alternative single-character separators.
1492 gboolean is_first = TRUE;
1493 gboolean have_leading = FALSE;
1494 const gchar *single_element = NULL;
1495 const gchar *next_element;
1496 const gchar *last_trailing = NULL;
1497 gchar current_separator = '\\';
1500 result = g_string_new (NULL);
1503 next_element = str_array[i++];
1505 next_element = first_element;
1509 const gchar *element;
1515 element = next_element;
1517 next_element = str_array[i++];
1519 next_element = va_arg (*args, gchar *);
1524 /* Ignore empty elements */
1533 (*start == '\\' || *start == '/'))
1535 current_separator = *start;
1540 end = start + strlen (start);
1544 while (end >= start + 1 &&
1545 (end[-1] == '\\' || end[-1] == '/'))
1547 current_separator = end[-1];
1551 last_trailing = end;
1552 while (last_trailing >= element + 1 &&
1553 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1558 /* If the leading and trailing separator strings are in the
1559 * same element and overlap, the result is exactly that element
1561 if (last_trailing <= start)
1562 single_element = element;
1564 g_string_append_len (result, element, start - element);
1565 have_leading = TRUE;
1568 single_element = NULL;
1575 g_string_append_len (result, ¤t_separator, 1);
1577 g_string_append_len (result, start, end - start);
1583 g_string_free (result, TRUE);
1584 return g_strdup (single_element);
1589 g_string_append (result, last_trailing);
1591 return g_string_free (result, FALSE);
1598 * g_build_filenamev:
1599 * @args: %NULL-terminated array of strings containing the path elements.
1601 * Behaves exactly like g_build_filename(), but takes the path elements
1602 * as a string array, instead of varargs. This function is mainly
1603 * meant for language bindings.
1605 * Return value: a newly-allocated string that must be freed with g_free().
1610 g_build_filenamev (gchar **args)
1615 str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1617 str = g_build_pathname_va (NULL, NULL, args);
1625 * @first_element: the first element in the path
1626 * @Varargs: remaining elements in path, terminated by %NULL
1628 * Creates a filename from a series of elements using the correct
1629 * separator for filenames.
1631 * On Unix, this function behaves identically to <literal>g_build_path
1632 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1634 * On Windows, it takes into account that either the backslash
1635 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1636 * as separator in filenames, but otherwise behaves as on Unix. When
1637 * file pathname separators need to be inserted, the one that last
1638 * previously occurred in the parameters (reading from left to right)
1641 * No attempt is made to force the resulting filename to be an absolute
1642 * path. If the first element is a relative path, the result will
1643 * be a relative path.
1645 * Return value: a newly-allocated string that must be freed with g_free().
1648 g_build_filename (const gchar *first_element,
1654 va_start (args, first_element);
1656 str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1658 str = g_build_pathname_va (first_element, &args, NULL);
1665 #define KILOBYTE_FACTOR 1024.0
1666 #define MEGABYTE_FACTOR (1024.0 * 1024.0)
1667 #define GIGABYTE_FACTOR (1024.0 * 1024.0 * 1024.0)
1670 * g_format_size_for_display:
1671 * @size: a size in bytes.
1673 * Formats a size (for example the size of a file) into a human readable string.
1674 * Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed
1675 * rounded to the nearest tenth. E.g. the file size 3292528 bytes will be
1676 * converted into the string "3.1 MB".
1678 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
1680 * This string should be freed with g_free() when not needed any longer.
1682 * Returns: a newly-allocated formatted string containing a human readable
1688 g_format_size_for_display (goffset size)
1690 if (size < (goffset) KILOBYTE_FACTOR)
1691 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
1694 gdouble displayed_size;
1696 if (size < (goffset) MEGABYTE_FACTOR)
1698 displayed_size = (gdouble) size / KILOBYTE_FACTOR;
1699 return g_strdup_printf (_("%.1f KB"), displayed_size);
1701 else if (size < (goffset) GIGABYTE_FACTOR)
1703 displayed_size = (gdouble) size / MEGABYTE_FACTOR;
1704 return g_strdup_printf (_("%.1f MB"), displayed_size);
1708 displayed_size = (gdouble) size / GIGABYTE_FACTOR;
1709 return g_strdup_printf (_("%.1f GB"), displayed_size);
1717 * @filename: the symbolic link
1718 * @error: return location for a #GError
1720 * Reads the contents of the symbolic link @filename like the POSIX
1721 * readlink() function. The returned string is in the encoding used
1722 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1724 * Returns: A newly-allocated string with the contents of the symbolic link,
1725 * or %NULL if an error occurred.
1730 g_file_read_link (const gchar *filename,
1733 #ifdef HAVE_READLINK
1739 buffer = g_malloc (size);
1743 read_size = readlink (filename, buffer, size);
1744 if (read_size < 0) {
1745 int save_errno = errno;
1746 gchar *display_filename = g_filename_display_name (filename);
1751 g_file_error_from_errno (save_errno),
1752 _("Failed to read the symbolic link '%s': %s"),
1754 g_strerror (save_errno));
1755 g_free (display_filename);
1760 if (read_size < size)
1762 buffer[read_size] = 0;
1767 buffer = g_realloc (buffer, size);
1770 g_set_error_literal (error,
1773 _("Symbolic links not supported"));
1779 /* NOTE : Keep this part last to ensure nothing in this file uses the
1780 * below binary compatibility versions.
1782 #if defined (G_OS_WIN32) && !defined (_WIN64)
1784 /* Binary compatibility versions. Will be called by code compiled
1785 * against quite old (pre-2.8, I think) headers only, not from more
1786 * recently compiled code.
1792 g_file_test (const gchar *filename,
1795 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
1798 if (utf8_filename == NULL)
1801 retval = g_file_test_utf8 (utf8_filename, test);
1803 g_free (utf8_filename);
1808 #undef g_file_get_contents
1811 g_file_get_contents (const gchar *filename,
1816 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
1819 if (utf8_filename == NULL)
1822 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
1824 g_free (utf8_filename);
1832 g_mkstemp (gchar *tmpl)
1836 static const char letters[] =
1837 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1838 static const int NLETTERS = sizeof (letters) - 1;
1841 static int counter = 0;
1843 /* find the last occurrence of 'XXXXXX' */
1844 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1852 /* Get some more or less random data. */
1853 g_get_current_time (&tv);
1854 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1856 for (count = 0; count < 100; value += 7777, ++count)
1860 /* Fill in the random bits. */
1861 XXXXXX[0] = letters[v % NLETTERS];
1863 XXXXXX[1] = letters[v % NLETTERS];
1865 XXXXXX[2] = letters[v % NLETTERS];
1867 XXXXXX[3] = letters[v % NLETTERS];
1869 XXXXXX[4] = letters[v % NLETTERS];
1871 XXXXXX[5] = letters[v % NLETTERS];
1873 /* This is the backward compatibility system codepage version,
1874 * thus use normal open().
1876 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1880 else if (errno != EEXIST)
1881 /* Any other error will apply also to other names we might
1882 * try, and there are 2^32 or so of them, so give up now.
1887 /* We got out of the loop because we ran out of combinations to try. */
1892 #undef g_file_open_tmp
1895 g_file_open_tmp (const gchar *tmpl,
1899 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1900 gchar *utf8_name_used;
1903 if (utf8_tmpl == NULL)
1906 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1912 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1914 g_free (utf8_name_used);
1921 #define __G_FILEUTILS_C__
1922 #include "galiasdef.c"