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
802 * @length: location to store length in bytes of the contents, or %NULL
803 * @error: return location for a #GError, or %NULL
805 * Reads an entire file into allocated memory, with good error
808 * If the call was successful, it returns %TRUE and sets @contents to the file
809 * contents and @length to the length of the file contents in bytes. The string
810 * stored in @contents will be nul-terminated, so for text files you can pass
811 * %NULL for the @length argument. If the call was not successful, it returns
812 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
813 * codes are those in the #GFileError enumeration. In the error case,
814 * @contents is set to %NULL and @length is set to zero.
816 * Return value: %TRUE on success, %FALSE if an error occurred
819 g_file_get_contents (const gchar *filename,
824 g_return_val_if_fail (filename != NULL, FALSE);
825 g_return_val_if_fail (contents != NULL, FALSE);
832 return get_contents_win32 (filename, contents, length, error);
834 return get_contents_posix (filename, contents, length, error);
839 rename_file (const char *old_name,
840 const char *new_name,
844 if (g_rename (old_name, new_name) == -1)
846 int save_errno = errno;
847 gchar *display_old_name = g_filename_display_name (old_name);
848 gchar *display_new_name = g_filename_display_name (new_name);
852 g_file_error_from_errno (save_errno),
853 _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
856 g_strerror (save_errno));
858 g_free (display_old_name);
859 g_free (display_new_name);
868 write_to_temp_file (const gchar *contents,
870 const gchar *template,
882 tmp_name = g_strdup_printf ("%s.XXXXXX", template);
885 fd = create_temp_file (tmp_name, 0666);
888 display_name = g_filename_display_name (tmp_name);
894 g_file_error_from_errno (save_errno),
895 _("Failed to create file '%s': %s"),
896 display_name, g_strerror (save_errno));
902 file = fdopen (fd, "wb");
908 g_file_error_from_errno (save_errno),
909 _("Failed to open file '%s' for writing: fdopen() failed: %s"),
911 g_strerror (save_errno));
925 n_written = fwrite (contents, 1, length, file);
927 if (n_written < length)
933 g_file_error_from_errno (save_errno),
934 _("Failed to write file '%s': fwrite() failed: %s"),
936 g_strerror (save_errno));
946 if (fclose (file) == EOF)
952 g_file_error_from_errno (save_errno),
953 _("Failed to close file '%s': fclose() failed: %s"),
955 g_strerror (save_errno));
962 retval = g_strdup (tmp_name);
966 g_free (display_name);
972 * g_file_set_contents:
973 * @filename: name of a file to write @contents to, in the GLib file name
975 * @contents: string to write to the file
976 * @length: length of @contents, or -1 if @contents is a nul-terminated string
977 * @error: return location for a #GError, or %NULL
979 * Writes all of @contents to a file named @filename, with good error checking.
980 * If a file called @filename already exists it will be overwritten.
982 * This write is atomic in the sense that it is first written to a temporary
983 * file which is then renamed to the final name. Notes:
986 * On Unix, if @filename already exists hard links to @filename will break.
987 * Also since the file is recreated, existing permissions, access control
988 * lists, metadata etc. may be lost. If @filename is a symbolic link,
989 * the link itself will be replaced, not the linked file.
992 * On Windows renaming a file will not remove an existing file with the
993 * new name, so on Windows there is a race condition between the existing
994 * file being removed and the temporary file being renamed.
997 * On Windows there is no way to remove a file that is open to some
998 * process, or mapped into memory. Thus, this function will fail if
999 * @filename already exists and is open.
1003 * If the call was sucessful, it returns %TRUE. If the call was not successful,
1004 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1005 * Possible error codes are those in the #GFileError enumeration.
1007 * Return value: %TRUE on success, %FALSE if an error occurred
1012 g_file_set_contents (const gchar *filename,
1013 const gchar *contents,
1017 gchar *tmp_filename;
1019 GError *rename_error = NULL;
1021 g_return_val_if_fail (filename != NULL, FALSE);
1022 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1023 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1024 g_return_val_if_fail (length >= -1, FALSE);
1027 length = strlen (contents);
1029 tmp_filename = write_to_temp_file (contents, length, filename, error);
1037 if (!rename_file (tmp_filename, filename, &rename_error))
1041 g_unlink (tmp_filename);
1042 g_propagate_error (error, rename_error);
1046 #else /* G_OS_WIN32 */
1048 /* Renaming failed, but on Windows this may just mean
1049 * the file already exists. So if the target file
1050 * exists, try deleting it and do the rename again.
1052 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1054 g_unlink (tmp_filename);
1055 g_propagate_error (error, rename_error);
1060 g_error_free (rename_error);
1062 if (g_unlink (filename) == -1)
1064 gchar *display_filename = g_filename_display_name (filename);
1066 int save_errno = errno;
1070 g_file_error_from_errno (save_errno),
1071 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1073 g_strerror (save_errno));
1075 g_free (display_filename);
1076 g_unlink (tmp_filename);
1081 if (!rename_file (tmp_filename, filename, error))
1083 g_unlink (tmp_filename);
1094 g_free (tmp_filename);
1099 * create_temp_file based on the mkstemp implementation from the GNU C library.
1100 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1103 create_temp_file (gchar *tmpl,
1108 static const char letters[] =
1109 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1110 static const int NLETTERS = sizeof (letters) - 1;
1113 static int counter = 0;
1115 /* find the last occurrence of "XXXXXX" */
1116 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1118 if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1124 /* Get some more or less random data. */
1125 g_get_current_time (&tv);
1126 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1128 for (count = 0; count < 100; value += 7777, ++count)
1132 /* Fill in the random bits. */
1133 XXXXXX[0] = letters[v % NLETTERS];
1135 XXXXXX[1] = letters[v % NLETTERS];
1137 XXXXXX[2] = letters[v % NLETTERS];
1139 XXXXXX[3] = letters[v % NLETTERS];
1141 XXXXXX[4] = letters[v % NLETTERS];
1143 XXXXXX[5] = letters[v % NLETTERS];
1145 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1146 fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, permissions);
1150 else if (errno != EEXIST)
1151 /* Any other error will apply also to other names we might
1152 * try, and there are 2^32 or so of them, so give up now.
1157 /* We got out of the loop because we ran out of combinations to try. */
1164 * @tmpl: template filename
1166 * Opens a temporary file. See the mkstemp() documentation
1167 * on most UNIX-like systems.
1169 * The parameter is a string that should follow the rules for
1170 * mkstemp() templates, i.e. contain the string "XXXXXX".
1171 * g_mkstemp() is slightly more flexible than mkstemp()
1172 * in that the sequence does not have to occur at the very end of the
1173 * template. The X string will
1174 * be modified to form the name of a file that didn't exist.
1175 * The string should be in the GLib file name encoding. Most importantly,
1176 * on Windows it should be in UTF-8.
1178 * Return value: A file handle (as from open()) to the file
1179 * opened for reading and writing. The file is opened in binary mode
1180 * on platforms where there is a difference. The file handle should be
1181 * closed with close(). In case of errors, -1 is returned.
1184 g_mkstemp (gchar *tmpl)
1186 return create_temp_file (tmpl, 0600);
1191 * @tmpl: Template for file name, as in g_mkstemp(), basename only,
1192 * or %NULL, to a default template
1193 * @name_used: location to store actual name used, or %NULL
1194 * @error: return location for a #GError
1196 * Opens a file for writing in the preferred directory for temporary
1197 * files (as returned by g_get_tmp_dir()).
1199 * @tmpl should be a string in the GLib file name encoding containing
1200 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1201 * However, unlike these functions, the template should only be a
1202 * basename, no directory components are allowed. If template is
1203 * %NULL, a default template is used.
1205 * Note that in contrast to g_mkstemp() (and mkstemp())
1206 * @tmpl is not modified, and might thus be a read-only literal string.
1208 * The actual name used is returned in @name_used if non-%NULL. This
1209 * string should be freed with g_free() when not needed any longer.
1210 * The returned name is in the GLib file name encoding.
1212 * Return value: A file handle (as from open()) to
1213 * the file opened for reading and writing. The file is opened in binary
1214 * mode on platforms where there is a difference. The file handle should be
1215 * closed with close(). In case of errors, -1 is returned
1216 * and @error will be set.
1219 g_file_open_tmp (const gchar *tmpl,
1232 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1234 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1238 gchar *display_tmpl = g_filename_display_name (tmpl);
1245 G_FILE_ERROR_FAILED,
1246 _("Template '%s' invalid, should not contain a '%s'"),
1248 g_free (display_tmpl);
1253 if (strstr (tmpl, "XXXXXX") == NULL)
1255 gchar *display_tmpl = g_filename_display_name (tmpl);
1258 G_FILE_ERROR_FAILED,
1259 _("Template '%s' doesn't contain XXXXXX"),
1261 g_free (display_tmpl);
1265 tmpdir = g_get_tmp_dir ();
1267 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1270 sep = G_DIR_SEPARATOR_S;
1272 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1274 retval = g_mkstemp (fulltemplate);
1278 int save_errno = errno;
1279 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1283 g_file_error_from_errno (save_errno),
1284 _("Failed to create file '%s': %s"),
1285 display_fulltemplate, g_strerror (save_errno));
1286 g_free (display_fulltemplate);
1287 g_free (fulltemplate);
1292 *name_used = fulltemplate;
1294 g_free (fulltemplate);
1300 g_build_path_va (const gchar *separator,
1301 const gchar *first_element,
1306 gint separator_len = strlen (separator);
1307 gboolean is_first = TRUE;
1308 gboolean have_leading = FALSE;
1309 const gchar *single_element = NULL;
1310 const gchar *next_element;
1311 const gchar *last_trailing = NULL;
1314 result = g_string_new (NULL);
1317 next_element = str_array[i++];
1319 next_element = first_element;
1323 const gchar *element;
1329 element = next_element;
1331 next_element = str_array[i++];
1333 next_element = va_arg (*args, gchar *);
1338 /* Ignore empty elements */
1347 strncmp (start, separator, separator_len) == 0)
1348 start += separator_len;
1351 end = start + strlen (start);
1355 while (end >= start + separator_len &&
1356 strncmp (end - separator_len, separator, separator_len) == 0)
1357 end -= separator_len;
1359 last_trailing = end;
1360 while (last_trailing >= element + separator_len &&
1361 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1362 last_trailing -= separator_len;
1366 /* If the leading and trailing separator strings are in the
1367 * same element and overlap, the result is exactly that element
1369 if (last_trailing <= start)
1370 single_element = element;
1372 g_string_append_len (result, element, start - element);
1373 have_leading = TRUE;
1376 single_element = NULL;
1383 g_string_append (result, separator);
1385 g_string_append_len (result, start, end - start);
1391 g_string_free (result, TRUE);
1392 return g_strdup (single_element);
1397 g_string_append (result, last_trailing);
1399 return g_string_free (result, FALSE);
1405 * @separator: a string used to separator the elements of the path.
1406 * @args: %NULL-terminated array of strings containing the path elements.
1408 * Behaves exactly like g_build_path(), but takes the path elements
1409 * as a string array, instead of varargs. This function is mainly
1410 * meant for language bindings.
1412 * Return value: a newly-allocated string that must be freed with g_free().
1417 g_build_pathv (const gchar *separator,
1423 return g_build_path_va (separator, NULL, NULL, args);
1429 * @separator: a string used to separator the elements of the path.
1430 * @first_element: the first element in the path
1431 * @Varargs: remaining elements in path, terminated by %NULL
1433 * Creates a path from a series of elements using @separator as the
1434 * separator between elements. At the boundary between two elements,
1435 * any trailing occurrences of separator in the first element, or
1436 * leading occurrences of separator in the second element are removed
1437 * and exactly one copy of the separator is inserted.
1439 * Empty elements are ignored.
1441 * The number of leading copies of the separator on the result is
1442 * the same as the number of leading copies of the separator on
1443 * the first non-empty element.
1445 * The number of trailing copies of the separator on the result is
1446 * the same as the number of trailing copies of the separator on
1447 * the last non-empty element. (Determination of the number of
1448 * trailing copies is done without stripping leading copies, so
1449 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1450 * has 1 trailing copy.)
1452 * However, if there is only a single non-empty element, and there
1453 * are no characters in that element not part of the leading or
1454 * trailing separators, then the result is exactly the original value
1457 * Other than for determination of the number of leading and trailing
1458 * copies of the separator, elements consisting only of copies
1459 * of the separator are ignored.
1461 * Return value: a newly-allocated string that must be freed with g_free().
1464 g_build_path (const gchar *separator,
1465 const gchar *first_element,
1471 g_return_val_if_fail (separator != NULL, NULL);
1473 va_start (args, first_element);
1474 str = g_build_path_va (separator, first_element, &args, NULL);
1483 g_build_pathname_va (const gchar *first_element,
1487 /* Code copied from g_build_pathv(), and modified to use two
1488 * alternative single-character separators.
1491 gboolean is_first = TRUE;
1492 gboolean have_leading = FALSE;
1493 const gchar *single_element = NULL;
1494 const gchar *next_element;
1495 const gchar *last_trailing = NULL;
1496 gchar current_separator = '\\';
1499 result = g_string_new (NULL);
1502 next_element = str_array[i++];
1504 next_element = first_element;
1508 const gchar *element;
1514 element = next_element;
1516 next_element = str_array[i++];
1518 next_element = va_arg (*args, gchar *);
1523 /* Ignore empty elements */
1532 (*start == '\\' || *start == '/'))
1534 current_separator = *start;
1539 end = start + strlen (start);
1543 while (end >= start + 1 &&
1544 (end[-1] == '\\' || end[-1] == '/'))
1546 current_separator = end[-1];
1550 last_trailing = end;
1551 while (last_trailing >= element + 1 &&
1552 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1557 /* If the leading and trailing separator strings are in the
1558 * same element and overlap, the result is exactly that element
1560 if (last_trailing <= start)
1561 single_element = element;
1563 g_string_append_len (result, element, start - element);
1564 have_leading = TRUE;
1567 single_element = NULL;
1574 g_string_append_len (result, ¤t_separator, 1);
1576 g_string_append_len (result, start, end - start);
1582 g_string_free (result, TRUE);
1583 return g_strdup (single_element);
1588 g_string_append (result, last_trailing);
1590 return g_string_free (result, FALSE);
1597 * g_build_filenamev:
1598 * @args: %NULL-terminated array of strings containing the path elements.
1600 * Behaves exactly like g_build_filename(), but takes the path elements
1601 * as a string array, instead of varargs. This function is mainly
1602 * meant for language bindings.
1604 * Return value: a newly-allocated string that must be freed with g_free().
1609 g_build_filenamev (gchar **args)
1614 str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1616 str = g_build_pathname_va (NULL, NULL, args);
1624 * @first_element: the first element in the path
1625 * @Varargs: remaining elements in path, terminated by %NULL
1627 * Creates a filename from a series of elements using the correct
1628 * separator for filenames.
1630 * On Unix, this function behaves identically to <literal>g_build_path
1631 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1633 * On Windows, it takes into account that either the backslash
1634 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1635 * as separator in filenames, but otherwise behaves as on Unix. When
1636 * file pathname separators need to be inserted, the one that last
1637 * previously occurred in the parameters (reading from left to right)
1640 * No attempt is made to force the resulting filename to be an absolute
1641 * path. If the first element is a relative path, the result will
1642 * be a relative path.
1644 * Return value: a newly-allocated string that must be freed with g_free().
1647 g_build_filename (const gchar *first_element,
1653 va_start (args, first_element);
1655 str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1657 str = g_build_pathname_va (first_element, &args, NULL);
1664 #define KILOBYTE_FACTOR 1024.0
1665 #define MEGABYTE_FACTOR (1024.0 * 1024.0)
1666 #define GIGABYTE_FACTOR (1024.0 * 1024.0 * 1024.0)
1669 * g_format_size_for_display:
1670 * @size: a size in bytes.
1672 * Formats a size (for example the size of a file) into a human readable string.
1673 * Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed
1674 * rounded to the nearest tenth. E.g. the file size 3292528 bytes will be
1675 * converted into the string "3.1 MB".
1677 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
1679 * This string should be freed with g_free() when not needed any longer.
1681 * Returns: a newly-allocated formatted string containing a human readable
1687 g_format_size_for_display (goffset size)
1689 if (size < (goffset) KILOBYTE_FACTOR)
1690 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
1693 gdouble displayed_size;
1695 if (size < (goffset) MEGABYTE_FACTOR)
1697 displayed_size = (gdouble) size / KILOBYTE_FACTOR;
1698 return g_strdup_printf (_("%.1f KB"), displayed_size);
1700 else if (size < (goffset) GIGABYTE_FACTOR)
1702 displayed_size = (gdouble) size / MEGABYTE_FACTOR;
1703 return g_strdup_printf (_("%.1f MB"), displayed_size);
1707 displayed_size = (gdouble) size / GIGABYTE_FACTOR;
1708 return g_strdup_printf (_("%.1f GB"), displayed_size);
1716 * @filename: the symbolic link
1717 * @error: return location for a #GError
1719 * Reads the contents of the symbolic link @filename like the POSIX
1720 * readlink() function. The returned string is in the encoding used
1721 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1723 * Returns: A newly-allocated string with the contents of the symbolic link,
1724 * or %NULL if an error occurred.
1729 g_file_read_link (const gchar *filename,
1732 #ifdef HAVE_READLINK
1738 buffer = g_malloc (size);
1742 read_size = readlink (filename, buffer, size);
1743 if (read_size < 0) {
1744 int save_errno = errno;
1745 gchar *display_filename = g_filename_display_name (filename);
1750 g_file_error_from_errno (save_errno),
1751 _("Failed to read the symbolic link '%s': %s"),
1753 g_strerror (save_errno));
1754 g_free (display_filename);
1759 if (read_size < size)
1761 buffer[read_size] = 0;
1766 buffer = g_realloc (buffer, size);
1769 g_set_error_literal (error,
1772 _("Symbolic links not supported"));
1778 /* NOTE : Keep this part last to ensure nothing in this file uses the
1779 * below binary compatibility versions.
1781 #if defined (G_OS_WIN32) && !defined (_WIN64)
1783 /* Binary compatibility versions. Will be called by code compiled
1784 * against quite old (pre-2.8, I think) headers only, not from more
1785 * recently compiled code.
1791 g_file_test (const gchar *filename,
1794 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
1797 if (utf8_filename == NULL)
1800 retval = g_file_test_utf8 (utf8_filename, test);
1802 g_free (utf8_filename);
1807 #undef g_file_get_contents
1810 g_file_get_contents (const gchar *filename,
1815 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
1818 if (utf8_filename == NULL)
1821 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
1823 g_free (utf8_filename);
1831 g_mkstemp (gchar *tmpl)
1835 static const char letters[] =
1836 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1837 static const int NLETTERS = sizeof (letters) - 1;
1840 static int counter = 0;
1842 /* find the last occurrence of 'XXXXXX' */
1843 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1851 /* Get some more or less random data. */
1852 g_get_current_time (&tv);
1853 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1855 for (count = 0; count < 100; value += 7777, ++count)
1859 /* Fill in the random bits. */
1860 XXXXXX[0] = letters[v % NLETTERS];
1862 XXXXXX[1] = letters[v % NLETTERS];
1864 XXXXXX[2] = letters[v % NLETTERS];
1866 XXXXXX[3] = letters[v % NLETTERS];
1868 XXXXXX[4] = letters[v % NLETTERS];
1870 XXXXXX[5] = letters[v % NLETTERS];
1872 /* This is the backward compatibility system codepage version,
1873 * thus use normal open().
1875 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1879 else if (errno != EEXIST)
1880 /* Any other error will apply also to other names we might
1881 * try, and there are 2^32 or so of them, so give up now.
1886 /* We got out of the loop because we ran out of combinations to try. */
1891 #undef g_file_open_tmp
1894 g_file_open_tmp (const gchar *tmpl,
1898 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1899 gchar *utf8_name_used;
1902 if (utf8_tmpl == NULL)
1905 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1911 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1913 g_free (utf8_name_used);
1920 #define __G_FILEUTILS_C__
1921 #include "galiasdef.c"