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 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)))
323 /* Binary compatibility version. Not for newly compiled code. */
326 g_file_test (const gchar *filename,
329 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
332 if (utf8_filename == NULL)
335 retval = g_file_test_utf8 (utf8_filename, test);
337 g_free (utf8_filename);
345 g_file_error_quark (void)
347 return g_quark_from_static_string ("g-file-error-quark");
351 * g_file_error_from_errno:
352 * @err_no: an "errno" value
354 * Gets a #GFileError constant based on the passed-in @errno.
355 * For example, if you pass in %EEXIST this function returns
356 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
357 * assume that all #GFileError values will exist.
359 * Normally a #GFileError value goes into a #GError returned
360 * from a function that manipulates files. So you would use
361 * g_file_error_from_errno() when constructing a #GError.
363 * Return value: #GFileError corresponding to the given @errno
366 g_file_error_from_errno (gint err_no)
372 return G_FILE_ERROR_EXIST;
378 return G_FILE_ERROR_ISDIR;
384 return G_FILE_ERROR_ACCES;
390 return G_FILE_ERROR_NAMETOOLONG;
396 return G_FILE_ERROR_NOENT;
402 return G_FILE_ERROR_NOTDIR;
408 return G_FILE_ERROR_NXIO;
414 return G_FILE_ERROR_NODEV;
420 return G_FILE_ERROR_ROFS;
426 return G_FILE_ERROR_TXTBSY;
432 return G_FILE_ERROR_FAULT;
438 return G_FILE_ERROR_LOOP;
444 return G_FILE_ERROR_NOSPC;
450 return G_FILE_ERROR_NOMEM;
456 return G_FILE_ERROR_MFILE;
462 return G_FILE_ERROR_NFILE;
468 return G_FILE_ERROR_BADF;
474 return G_FILE_ERROR_INVAL;
480 return G_FILE_ERROR_PIPE;
486 return G_FILE_ERROR_AGAIN;
492 return G_FILE_ERROR_INTR;
498 return G_FILE_ERROR_IO;
504 return G_FILE_ERROR_PERM;
510 return G_FILE_ERROR_NOSYS;
515 return G_FILE_ERROR_FAILED;
521 get_contents_stdio (const gchar *display_filename,
530 gsize total_bytes = 0;
531 gsize total_allocated = 0;
534 g_assert (f != NULL);
540 bytes = fread (buf, 1, sizeof (buf), f);
543 while ((total_bytes + bytes + 1) > total_allocated)
546 total_allocated *= 2;
548 total_allocated = MIN (bytes + 1, sizeof (buf));
550 tmp = g_try_realloc (str, total_allocated);
557 _("Could not allocate %lu bytes to read file \"%s\""),
558 (gulong) total_allocated,
571 g_file_error_from_errno (save_errno),
572 _("Error reading file '%s': %s"),
574 g_strerror (save_errno));
579 memcpy (str + total_bytes, buf, bytes);
580 total_bytes += bytes;
585 if (total_allocated == 0)
586 str = g_new (gchar, 1);
588 str[total_bytes] = '\0';
591 *length = total_bytes;
608 get_contents_regfile (const gchar *display_filename,
609 struct stat *stat_buf,
620 size = stat_buf->st_size;
622 alloc_size = size + 1;
623 buf = g_try_malloc (alloc_size);
630 _("Could not allocate %lu bytes to read file \"%s\""),
638 while (bytes_read < size)
642 rc = read (fd, buf + bytes_read, size - bytes_read);
648 int save_errno = errno;
653 g_file_error_from_errno (save_errno),
654 _("Failed to read from file '%s': %s"),
656 g_strerror (save_errno));
667 buf[bytes_read] = '\0';
670 *length = bytes_read;
686 get_contents_posix (const gchar *filename,
691 struct stat stat_buf;
693 gchar *display_filename = g_filename_display_name (filename);
695 /* O_BINARY useful on Cygwin */
696 fd = open (filename, O_RDONLY|O_BINARY);
700 int save_errno = errno;
704 g_file_error_from_errno (save_errno),
705 _("Failed to open file '%s': %s"),
707 g_strerror (save_errno));
708 g_free (display_filename);
713 /* I don't think this will ever fail, aside from ENOMEM, but. */
714 if (fstat (fd, &stat_buf) < 0)
716 int save_errno = errno;
721 g_file_error_from_errno (save_errno),
722 _("Failed to get attributes of file '%s': fstat() failed: %s"),
724 g_strerror (save_errno));
725 g_free (display_filename);
730 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
732 gboolean retval = get_contents_regfile (display_filename,
738 g_free (display_filename);
747 f = fdopen (fd, "r");
751 int save_errno = errno;
755 g_file_error_from_errno (save_errno),
756 _("Failed to open file '%s': fdopen() failed: %s"),
758 g_strerror (save_errno));
759 g_free (display_filename);
764 retval = get_contents_stdio (display_filename, f, contents, length, error);
765 g_free (display_filename);
771 #else /* G_OS_WIN32 */
774 get_contents_win32 (const gchar *filename,
781 gchar *display_filename = g_filename_display_name (filename);
784 f = g_fopen (filename, "rb");
791 g_file_error_from_errno (save_errno),
792 _("Failed to open file '%s': %s"),
794 g_strerror (save_errno));
795 g_free (display_filename);
800 retval = get_contents_stdio (display_filename, f, contents, length, error);
801 g_free (display_filename);
809 * g_file_get_contents:
810 * @filename: name of a file to read contents from, in the GLib file name encoding
811 * @contents: location to store an allocated string
812 * @length: location to store length in bytes of the contents, or %NULL
813 * @error: return location for a #GError, or %NULL
815 * Reads an entire file into allocated memory, with good error
818 * If the call was successful, it returns %TRUE and sets @contents to the file
819 * contents and @length to the length of the file contents in bytes. The string
820 * stored in @contents will be nul-terminated, so for text files you can pass
821 * %NULL for the @length argument. If the call was not successful, it returns
822 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
823 * codes are those in the #GFileError enumeration. In the error case,
824 * @contents is set to %NULL and @length is set to zero.
826 * Return value: %TRUE on success, %FALSE if an error occurred
829 g_file_get_contents (const gchar *filename,
834 g_return_val_if_fail (filename != NULL, FALSE);
835 g_return_val_if_fail (contents != NULL, FALSE);
842 return get_contents_win32 (filename, contents, length, error);
844 return get_contents_posix (filename, contents, length, error);
850 #undef g_file_get_contents
852 /* Binary compatibility version. Not for newly compiled code. */
855 g_file_get_contents (const gchar *filename,
860 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
863 if (utf8_filename == NULL)
866 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
868 g_free (utf8_filename);
876 rename_file (const char *old_name,
877 const char *new_name,
881 if (g_rename (old_name, new_name) == -1)
883 int save_errno = errno;
884 gchar *display_old_name = g_filename_display_name (old_name);
885 gchar *display_new_name = g_filename_display_name (new_name);
889 g_file_error_from_errno (save_errno),
890 _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
893 g_strerror (save_errno));
895 g_free (display_old_name);
896 g_free (display_new_name);
905 write_to_temp_file (const gchar *contents,
907 const gchar *template,
919 tmp_name = g_strdup_printf ("%s.XXXXXX", template);
922 fd = create_temp_file (tmp_name, 0666);
925 display_name = g_filename_display_name (tmp_name);
931 g_file_error_from_errno (save_errno),
932 _("Failed to create file '%s': %s"),
933 display_name, g_strerror (save_errno));
939 file = fdopen (fd, "wb");
945 g_file_error_from_errno (save_errno),
946 _("Failed to open file '%s' for writing: fdopen() failed: %s"),
948 g_strerror (save_errno));
962 n_written = fwrite (contents, 1, length, file);
964 if (n_written < length)
970 g_file_error_from_errno (save_errno),
971 _("Failed to write file '%s': fwrite() failed: %s"),
973 g_strerror (save_errno));
983 if (fclose (file) == EOF)
989 g_file_error_from_errno (save_errno),
990 _("Failed to close file '%s': fclose() failed: %s"),
992 g_strerror (save_errno));
999 retval = g_strdup (tmp_name);
1003 g_free (display_name);
1009 * g_file_set_contents:
1010 * @filename: name of a file to write @contents to, in the GLib file name
1012 * @contents: string to write to the file
1013 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1014 * @error: return location for a #GError, or %NULL
1016 * Writes all of @contents to a file named @filename, with good error checking.
1017 * If a file called @filename already exists it will be overwritten.
1019 * This write is atomic in the sense that it is first written to a temporary
1020 * file which is then renamed to the final name. Notes:
1023 * On Unix, if @filename already exists hard links to @filename will break.
1024 * Also since the file is recreated, existing permissions, access control
1025 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1026 * the link itself will be replaced, not the linked file.
1029 * On Windows renaming a file will not remove an existing file with the
1030 * new name, so on Windows there is a race condition between the existing
1031 * file being removed and the temporary file being renamed.
1034 * On Windows there is no way to remove a file that is open to some
1035 * process, or mapped into memory. Thus, this function will fail if
1036 * @filename already exists and is open.
1040 * If the call was sucessful, it returns %TRUE. If the call was not successful,
1041 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1042 * Possible error codes are those in the #GFileError enumeration.
1044 * Return value: %TRUE on success, %FALSE if an error occurred
1049 g_file_set_contents (const gchar *filename,
1050 const gchar *contents,
1054 gchar *tmp_filename;
1056 GError *rename_error = NULL;
1058 g_return_val_if_fail (filename != NULL, FALSE);
1059 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1060 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1061 g_return_val_if_fail (length >= -1, FALSE);
1064 length = strlen (contents);
1066 tmp_filename = write_to_temp_file (contents, length, filename, error);
1074 if (!rename_file (tmp_filename, filename, &rename_error))
1078 g_unlink (tmp_filename);
1079 g_propagate_error (error, rename_error);
1083 #else /* G_OS_WIN32 */
1085 /* Renaming failed, but on Windows this may just mean
1086 * the file already exists. So if the target file
1087 * exists, try deleting it and do the rename again.
1089 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1091 g_unlink (tmp_filename);
1092 g_propagate_error (error, rename_error);
1097 g_error_free (rename_error);
1099 if (g_unlink (filename) == -1)
1101 gchar *display_filename = g_filename_display_name (filename);
1103 int save_errno = errno;
1107 g_file_error_from_errno (save_errno),
1108 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1110 g_strerror (save_errno));
1112 g_free (display_filename);
1113 g_unlink (tmp_filename);
1118 if (!rename_file (tmp_filename, filename, error))
1120 g_unlink (tmp_filename);
1131 g_free (tmp_filename);
1136 * create_temp_file based on the mkstemp implementation from the GNU C library.
1137 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1140 create_temp_file (gchar *tmpl,
1145 static const char letters[] =
1146 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1147 static const int NLETTERS = sizeof (letters) - 1;
1150 static int counter = 0;
1152 /* find the last occurrence of "XXXXXX" */
1153 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1155 if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1161 /* Get some more or less random data. */
1162 g_get_current_time (&tv);
1163 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1165 for (count = 0; count < 100; value += 7777, ++count)
1169 /* Fill in the random bits. */
1170 XXXXXX[0] = letters[v % NLETTERS];
1172 XXXXXX[1] = letters[v % NLETTERS];
1174 XXXXXX[2] = letters[v % NLETTERS];
1176 XXXXXX[3] = letters[v % NLETTERS];
1178 XXXXXX[4] = letters[v % NLETTERS];
1180 XXXXXX[5] = letters[v % NLETTERS];
1182 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1183 fd = g_open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, permissions);
1187 else if (errno != EEXIST)
1188 /* Any other error will apply also to other names we might
1189 * try, and there are 2^32 or so of them, so give up now.
1194 /* We got out of the loop because we ran out of combinations to try. */
1201 * @tmpl: template filename
1203 * Opens a temporary file. See the mkstemp() documentation
1204 * on most UNIX-like systems.
1206 * The parameter is a string that should follow the rules for
1207 * mkstemp() templates, i.e. contain the string "XXXXXX".
1208 * g_mkstemp() is slightly more flexible than mkstemp()
1209 * in that the sequence does not have to occur at the very end of the
1210 * template. The X string will
1211 * be modified to form the name of a file that didn't exist.
1212 * The string should be in the GLib file name encoding. Most importantly,
1213 * on Windows it should be in UTF-8.
1215 * Return value: A file handle (as from open()) to the file
1216 * opened for reading and writing. The file is opened in binary mode
1217 * on platforms where there is a difference. The file handle should be
1218 * closed with close(). In case of errors, -1 is returned.
1221 g_mkstemp (gchar *tmpl)
1223 return create_temp_file (tmpl, 0600);
1230 /* Binary compatibility version. Not for newly compiled code. */
1233 g_mkstemp (gchar *tmpl)
1237 static const char letters[] =
1238 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1239 static const int NLETTERS = sizeof (letters) - 1;
1242 static int counter = 0;
1244 /* find the last occurrence of 'XXXXXX' */
1245 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1247 if (!XXXXXX || strcmp (XXXXXX, "XXXXXX"))
1253 /* Get some more or less random data. */
1254 g_get_current_time (&tv);
1255 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1257 for (count = 0; count < 100; value += 7777, ++count)
1261 /* Fill in the random bits. */
1262 XXXXXX[0] = letters[v % NLETTERS];
1264 XXXXXX[1] = letters[v % NLETTERS];
1266 XXXXXX[2] = letters[v % NLETTERS];
1268 XXXXXX[3] = letters[v % NLETTERS];
1270 XXXXXX[4] = letters[v % NLETTERS];
1272 XXXXXX[5] = letters[v % NLETTERS];
1274 /* This is the backward compatibility system codepage version,
1275 * thus use normal open().
1277 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1281 else if (errno != EEXIST)
1282 /* Any other error will apply also to other names we might
1283 * try, and there are 2^32 or so of them, so give up now.
1288 /* We got out of the loop because we ran out of combinations to try. */
1297 * @tmpl: Template for file name, as in g_mkstemp(), basename only,
1298 * or %NULL, to a default template
1299 * @name_used: location to store actual name used
1300 * @error: return location for a #GError
1302 * Opens a file for writing in the preferred directory for temporary
1303 * files (as returned by g_get_tmp_dir()).
1305 * @tmpl should be a string in the GLib file name encoding containing
1306 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1307 * However, unlike these functions, the template should only be a
1308 * basename, no directory components are allowed. If template is
1309 * %NULL, a default template is used.
1311 * Note that in contrast to g_mkstemp() (and mkstemp())
1312 * @tmpl is not modified, and might thus be a read-only literal string.
1314 * The actual name used is returned in @name_used if non-%NULL. This
1315 * string should be freed with g_free() when not needed any longer.
1316 * The returned name is in the GLib file name encoding.
1318 * Return value: A file handle (as from open()) to
1319 * the file opened for reading and writing. The file is opened in binary
1320 * mode on platforms where there is a difference. The file handle should be
1321 * closed with close(). In case of errors, -1 is returned
1322 * and @error will be set.
1325 g_file_open_tmp (const gchar *tmpl,
1338 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1340 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1344 gchar *display_tmpl = g_filename_display_name (tmpl);
1351 G_FILE_ERROR_FAILED,
1352 _("Template '%s' invalid, should not contain a '%s'"),
1354 g_free (display_tmpl);
1359 if (strstr (tmpl, "XXXXXX") == NULL)
1361 gchar *display_tmpl = g_filename_display_name (tmpl);
1364 G_FILE_ERROR_FAILED,
1365 _("Template '%s' doesn't contain XXXXXX"),
1367 g_free (display_tmpl);
1371 tmpdir = g_get_tmp_dir ();
1373 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1376 sep = G_DIR_SEPARATOR_S;
1378 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1380 retval = g_mkstemp (fulltemplate);
1384 int save_errno = errno;
1385 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1389 g_file_error_from_errno (save_errno),
1390 _("Failed to create file '%s': %s"),
1391 display_fulltemplate, g_strerror (save_errno));
1392 g_free (display_fulltemplate);
1393 g_free (fulltemplate);
1398 *name_used = fulltemplate;
1400 g_free (fulltemplate);
1407 #undef g_file_open_tmp
1409 /* Binary compatibility version. Not for newly compiled code. */
1412 g_file_open_tmp (const gchar *tmpl,
1416 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1417 gchar *utf8_name_used;
1420 if (utf8_tmpl == NULL)
1423 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
1429 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
1431 g_free (utf8_name_used);
1439 g_build_path_va (const gchar *separator,
1440 const gchar *first_element,
1445 gint separator_len = strlen (separator);
1446 gboolean is_first = TRUE;
1447 gboolean have_leading = FALSE;
1448 const gchar *single_element = NULL;
1449 const gchar *next_element;
1450 const gchar *last_trailing = NULL;
1453 result = g_string_new (NULL);
1456 next_element = str_array[i++];
1458 next_element = first_element;
1462 const gchar *element;
1468 element = next_element;
1470 next_element = str_array[i++];
1472 next_element = va_arg (*args, gchar *);
1477 /* Ignore empty elements */
1486 strncmp (start, separator, separator_len) == 0)
1487 start += separator_len;
1490 end = start + strlen (start);
1494 while (end >= start + separator_len &&
1495 strncmp (end - separator_len, separator, separator_len) == 0)
1496 end -= separator_len;
1498 last_trailing = end;
1499 while (last_trailing >= element + separator_len &&
1500 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1501 last_trailing -= separator_len;
1505 /* If the leading and trailing separator strings are in the
1506 * same element and overlap, the result is exactly that element
1508 if (last_trailing <= start)
1509 single_element = element;
1511 g_string_append_len (result, element, start - element);
1512 have_leading = TRUE;
1515 single_element = NULL;
1522 g_string_append (result, separator);
1524 g_string_append_len (result, start, end - start);
1530 g_string_free (result, TRUE);
1531 return g_strdup (single_element);
1536 g_string_append (result, last_trailing);
1538 return g_string_free (result, FALSE);
1544 * @separator: a string used to separator the elements of the path.
1545 * @args: %NULL-terminated array of strings containing the path elements.
1547 * Behaves exactly like g_build_path(), but takes the path elements
1548 * as a string array, instead of varargs. This function is mainly
1549 * meant for language bindings.
1551 * Return value: a newly-allocated string that must be freed with g_free().
1556 g_build_pathv (const gchar *separator,
1562 return g_build_path_va (separator, NULL, NULL, args);
1568 * @separator: a string used to separator the elements of the path.
1569 * @first_element: the first element in the path
1570 * @Varargs: remaining elements in path, terminated by %NULL
1572 * Creates a path from a series of elements using @separator as the
1573 * separator between elements. At the boundary between two elements,
1574 * any trailing occurrences of separator in the first element, or
1575 * leading occurrences of separator in the second element are removed
1576 * and exactly one copy of the separator is inserted.
1578 * Empty elements are ignored.
1580 * The number of leading copies of the separator on the result is
1581 * the same as the number of leading copies of the separator on
1582 * the first non-empty element.
1584 * The number of trailing copies of the separator on the result is
1585 * the same as the number of trailing copies of the separator on
1586 * the last non-empty element. (Determination of the number of
1587 * trailing copies is done without stripping leading copies, so
1588 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1589 * has 1 trailing copy.)
1591 * However, if there is only a single non-empty element, and there
1592 * are no characters in that element not part of the leading or
1593 * trailing separators, then the result is exactly the original value
1596 * Other than for determination of the number of leading and trailing
1597 * copies of the separator, elements consisting only of copies
1598 * of the separator are ignored.
1600 * Return value: a newly-allocated string that must be freed with g_free().
1603 g_build_path (const gchar *separator,
1604 const gchar *first_element,
1610 g_return_val_if_fail (separator != NULL, NULL);
1612 va_start (args, first_element);
1613 str = g_build_path_va (separator, first_element, &args, NULL);
1622 g_build_pathname_va (const gchar *first_element,
1626 /* Code copied from g_build_pathv(), and modified to use two
1627 * alternative single-character separators.
1630 gboolean is_first = TRUE;
1631 gboolean have_leading = FALSE;
1632 const gchar *single_element = NULL;
1633 const gchar *next_element;
1634 const gchar *last_trailing = NULL;
1635 gchar current_separator = '\\';
1638 result = g_string_new (NULL);
1641 next_element = str_array[i++];
1643 next_element = first_element;
1647 const gchar *element;
1653 element = next_element;
1655 next_element = str_array[i++];
1657 next_element = va_arg (*args, gchar *);
1662 /* Ignore empty elements */
1671 (*start == '\\' || *start == '/'))
1673 current_separator = *start;
1678 end = start + strlen (start);
1682 while (end >= start + 1 &&
1683 (end[-1] == '\\' || end[-1] == '/'))
1685 current_separator = end[-1];
1689 last_trailing = end;
1690 while (last_trailing >= element + 1 &&
1691 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1696 /* If the leading and trailing separator strings are in the
1697 * same element and overlap, the result is exactly that element
1699 if (last_trailing <= start)
1700 single_element = element;
1702 g_string_append_len (result, element, start - element);
1703 have_leading = TRUE;
1706 single_element = NULL;
1713 g_string_append_len (result, ¤t_separator, 1);
1715 g_string_append_len (result, start, end - start);
1721 g_string_free (result, TRUE);
1722 return g_strdup (single_element);
1727 g_string_append (result, last_trailing);
1729 return g_string_free (result, FALSE);
1736 * g_build_filenamev:
1737 * @args: %NULL-terminated array of strings containing the path elements.
1739 * Behaves exactly like g_build_filename(), but takes the path elements
1740 * as a string array, instead of varargs. This function is mainly
1741 * meant for language bindings.
1743 * Return value: a newly-allocated string that must be freed with g_free().
1748 g_build_filenamev (gchar **args)
1753 str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1755 str = g_build_pathname_va (NULL, NULL, args);
1763 * @first_element: the first element in the path
1764 * @Varargs: remaining elements in path, terminated by %NULL
1766 * Creates a filename from a series of elements using the correct
1767 * separator for filenames.
1769 * On Unix, this function behaves identically to <literal>g_build_path
1770 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1772 * On Windows, it takes into account that either the backslash
1773 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1774 * as separator in filenames, but otherwise behaves as on Unix. When
1775 * file pathname separators need to be inserted, the one that last
1776 * previously occurred in the parameters (reading from left to right)
1779 * No attempt is made to force the resulting filename to be an absolute
1780 * path. If the first element is a relative path, the result will
1781 * be a relative path.
1783 * Return value: a newly-allocated string that must be freed with g_free().
1786 g_build_filename (const gchar *first_element,
1792 va_start (args, first_element);
1794 str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1796 str = g_build_pathname_va (first_element, &args, NULL);
1803 #define KILOBYTE_FACTOR 1024.0
1804 #define MEGABYTE_FACTOR (1024.0 * 1024.0)
1805 #define GIGABYTE_FACTOR (1024.0 * 1024.0 * 1024.0)
1808 * g_format_file_size_for_display:
1809 * @size: a file size.
1811 * Formats a file size into a human readable string. Sizes are rounded
1812 * to the nearest metric prefix and are displayed rounded to the nearest
1813 * tenth. E.g. the file size 3292528 bytes will be converted into the string
1816 * Returns: a formatted string containing a human readable file size.
1821 g_format_file_size_for_display (goffset size)
1823 if (size < (goffset) KILOBYTE_FACTOR)
1824 return g_strdup_printf (dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
1827 gdouble displayed_size;
1829 if (size < (goffset) MEGABYTE_FACTOR)
1831 displayed_size = (gdouble) size / KILOBYTE_FACTOR;
1832 return g_strdup_printf (_("%.1f KB"), displayed_size);
1834 else if (size < (goffset) GIGABYTE_FACTOR)
1836 displayed_size = (gdouble) size / MEGABYTE_FACTOR;
1837 return g_strdup_printf (_("%.1f MB"), displayed_size);
1841 displayed_size = (gdouble) size / GIGABYTE_FACTOR;
1842 return g_strdup_printf (_("%.1f GB"), displayed_size);
1850 * @filename: the symbolic link
1851 * @error: return location for a #GError
1853 * Reads the contents of the symbolic link @filename like the POSIX
1854 * readlink() function. The returned string is in the encoding used
1855 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1857 * Returns: A newly allocated string with the contents of the symbolic link,
1858 * or %NULL if an error occurred.
1863 g_file_read_link (const gchar *filename,
1866 #ifdef HAVE_READLINK
1872 buffer = g_malloc (size);
1876 read_size = readlink (filename, buffer, size);
1877 if (read_size < 0) {
1878 int save_errno = errno;
1879 gchar *display_filename = g_filename_display_name (filename);
1884 g_file_error_from_errno (save_errno),
1885 _("Failed to read the symbolic link '%s': %s"),
1887 g_strerror (save_errno));
1888 g_free (display_filename);
1893 if (read_size < size)
1895 buffer[read_size] = 0;
1900 buffer = g_realloc (buffer, size);
1906 _("Symbolic links not supported"));
1912 #define __G_FILEUTILS_C__
1913 #include "galiasdef.c"