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 * g_mkdir_with_parents:
58 * @pathname: a pathname in the GLib file name encoding
59 * @mode: permissions to use for newly created directories
61 * Create a directory if it doesn't already exist. Create intermediate
62 * parent directories as needed, too.
64 * Returns: 0 if the directory already exists, or was successfully
65 * created. Returns -1 if an error occurred, with errno set.
70 g_mkdir_with_parents (const gchar *pathname,
75 if (pathname == NULL || *pathname == '\0')
81 fn = g_strdup (pathname);
83 if (g_path_is_absolute (fn))
84 p = (gchar *) g_path_skip_root (fn);
90 while (*p && !G_IS_DIR_SEPARATOR (*p))
98 if (!g_file_test (fn, G_FILE_TEST_EXISTS))
100 if (g_mkdir (fn, mode) == -1)
102 int errno_save = errno;
108 else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
116 *p++ = G_DIR_SEPARATOR;
117 while (*p && G_IS_DIR_SEPARATOR (*p))
130 * @filename: a filename to test in the GLib file name encoding
131 * @test: bitfield of #GFileTest flags
133 * Returns %TRUE if any of the tests in the bitfield @test are
134 * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS |
135 * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists;
136 * the check whether it's a directory doesn't matter since the existence
137 * test is %TRUE. With the current set of available tests, there's no point
138 * passing in more than one test at a time.
140 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
141 * so for a symbolic link to a regular file g_file_test() will return
142 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
144 * Note, that for a dangling symbolic link g_file_test() will return
145 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
147 * You should never use g_file_test() to test whether it is safe
148 * to perform an operation, because there is always the possibility
149 * of the condition changing before you actually perform the operation.
150 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
151 * to know whether it is safe to write to a file without being
152 * tricked into writing into a different location. It doesn't work!
154 * /* DON'T DO THIS */
155 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
157 * fd = g_open (filename, O_WRONLY);
158 * /* write to fd */
162 * Another thing to note is that %G_FILE_TEST_EXISTS and
163 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
164 * system call. This usually doesn't matter, but if your program
165 * is setuid or setgid it means that these tests will give you
166 * the answer for the real user ID and group ID, rather than the
167 * effective user ID and group ID.
169 * On Windows, there are no symlinks, so testing for
170 * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
171 * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
172 * its name indicates that it is executable, checking for well-known
173 * extensions and those listed in the %PATHEXT environment variable.
175 * Return value: whether a test was %TRUE
178 g_file_test (const gchar *filename,
182 /* stuff missing in std vc6 api */
183 # ifndef INVALID_FILE_ATTRIBUTES
184 # define INVALID_FILE_ATTRIBUTES -1
186 # ifndef FILE_ATTRIBUTE_DEVICE
187 # define FILE_ATTRIBUTE_DEVICE 64
190 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
192 if (wfilename == NULL)
195 attributes = GetFileAttributesW (wfilename);
199 if (attributes == INVALID_FILE_ATTRIBUTES)
202 if (test & G_FILE_TEST_EXISTS)
205 if (test & G_FILE_TEST_IS_REGULAR)
207 if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0)
211 if (test & G_FILE_TEST_IS_DIR)
213 if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
217 /* "while" so that we can exit this "loop" with a simple "break" */
218 while (test & G_FILE_TEST_IS_EXECUTABLE)
220 const gchar *lastdot = strrchr (filename, '.');
221 const gchar *pathext = NULL, *p;
227 if (_stricmp (lastdot, ".exe") == 0 ||
228 _stricmp (lastdot, ".cmd") == 0 ||
229 _stricmp (lastdot, ".bat") == 0 ||
230 _stricmp (lastdot, ".com") == 0)
233 /* Check if it is one of the types listed in %PATHEXT% */
235 pathext = g_getenv ("PATHEXT");
239 pathext = g_utf8_casefold (pathext, -1);
241 lastdot = g_utf8_casefold (lastdot, -1);
242 extlen = strlen (lastdot);
247 const gchar *q = strchr (p, ';');
250 if (extlen == q - p &&
251 memcmp (lastdot, p, extlen) == 0)
253 g_free ((gchar *) pathext);
254 g_free ((gchar *) lastdot);
263 g_free ((gchar *) pathext);
264 g_free ((gchar *) lastdot);
270 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
273 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
278 /* For root, on some POSIX systems, access (filename, X_OK)
279 * will succeed even if no executable bits are set on the
280 * file. We fall through to a stat test to avoid that.
284 test &= ~G_FILE_TEST_IS_EXECUTABLE;
286 if (test & G_FILE_TEST_IS_SYMLINK)
290 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
294 if (test & (G_FILE_TEST_IS_REGULAR |
296 G_FILE_TEST_IS_EXECUTABLE))
300 if (stat (filename, &s) == 0)
302 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
305 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
308 /* The extra test for root when access (file, X_OK) succeeds.
310 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
311 ((s.st_mode & S_IXOTH) ||
312 (s.st_mode & S_IXUSR) ||
313 (s.st_mode & S_IXGRP)))
323 g_file_error_quark (void)
325 return g_quark_from_static_string ("g-file-error-quark");
329 * g_file_error_from_errno:
330 * @err_no: an "errno" value
332 * Gets a #GFileError constant based on the passed-in @errno.
333 * For example, if you pass in %EEXIST this function returns
334 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
335 * assume that all #GFileError values will exist.
337 * Normally a #GFileError value goes into a #GError returned
338 * from a function that manipulates files. So you would use
339 * g_file_error_from_errno() when constructing a #GError.
341 * Return value: #GFileError corresponding to the given @errno
344 g_file_error_from_errno (gint err_no)
350 return G_FILE_ERROR_EXIST;
356 return G_FILE_ERROR_ISDIR;
362 return G_FILE_ERROR_ACCES;
368 return G_FILE_ERROR_NAMETOOLONG;
374 return G_FILE_ERROR_NOENT;
380 return G_FILE_ERROR_NOTDIR;
386 return G_FILE_ERROR_NXIO;
392 return G_FILE_ERROR_NODEV;
398 return G_FILE_ERROR_ROFS;
404 return G_FILE_ERROR_TXTBSY;
410 return G_FILE_ERROR_FAULT;
416 return G_FILE_ERROR_LOOP;
422 return G_FILE_ERROR_NOSPC;
428 return G_FILE_ERROR_NOMEM;
434 return G_FILE_ERROR_MFILE;
440 return G_FILE_ERROR_NFILE;
446 return G_FILE_ERROR_BADF;
452 return G_FILE_ERROR_INVAL;
458 return G_FILE_ERROR_PIPE;
464 return G_FILE_ERROR_AGAIN;
470 return G_FILE_ERROR_INTR;
476 return G_FILE_ERROR_IO;
482 return G_FILE_ERROR_PERM;
488 return G_FILE_ERROR_NOSYS;
493 return G_FILE_ERROR_FAILED;
499 get_contents_stdio (const gchar *display_filename,
508 gsize total_bytes = 0;
509 gsize total_allocated = 0;
512 g_assert (f != NULL);
518 bytes = fread (buf, 1, sizeof (buf), f);
521 while ((total_bytes + bytes + 1) > total_allocated)
524 total_allocated *= 2;
526 total_allocated = MIN (bytes + 1, sizeof (buf));
528 tmp = g_try_realloc (str, total_allocated);
535 _("Could not allocate %lu bytes to read file \"%s\""),
536 (gulong) total_allocated,
549 g_file_error_from_errno (save_errno),
550 _("Error reading file '%s': %s"),
552 g_strerror (save_errno));
557 memcpy (str + total_bytes, buf, bytes);
559 if (total_bytes + bytes < total_bytes)
564 _("File \"%s\" is too large"),
570 total_bytes += bytes;
575 if (total_allocated == 0)
577 str = g_new (gchar, 1);
581 str[total_bytes] = '\0';
584 *length = total_bytes;
601 get_contents_regfile (const gchar *display_filename,
602 struct stat *stat_buf,
613 size = stat_buf->st_size;
615 alloc_size = size + 1;
616 buf = g_try_malloc (alloc_size);
623 _("Could not allocate %lu bytes to read file \"%s\""),
631 while (bytes_read < size)
635 rc = read (fd, buf + bytes_read, size - bytes_read);
641 int save_errno = errno;
646 g_file_error_from_errno (save_errno),
647 _("Failed to read from file '%s': %s"),
649 g_strerror (save_errno));
660 buf[bytes_read] = '\0';
663 *length = bytes_read;
679 get_contents_posix (const gchar *filename,
684 struct stat stat_buf;
686 gchar *display_filename = g_filename_display_name (filename);
688 /* O_BINARY useful on Cygwin */
689 fd = open (filename, O_RDONLY|O_BINARY);
693 int save_errno = errno;
697 g_file_error_from_errno (save_errno),
698 _("Failed to open file '%s': %s"),
700 g_strerror (save_errno));
701 g_free (display_filename);
706 /* I don't think this will ever fail, aside from ENOMEM, but. */
707 if (fstat (fd, &stat_buf) < 0)
709 int save_errno = errno;
714 g_file_error_from_errno (save_errno),
715 _("Failed to get attributes of file '%s': fstat() failed: %s"),
717 g_strerror (save_errno));
718 g_free (display_filename);
723 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
725 gboolean retval = get_contents_regfile (display_filename,
731 g_free (display_filename);
740 f = fdopen (fd, "r");
744 int save_errno = errno;
748 g_file_error_from_errno (save_errno),
749 _("Failed to open file '%s': fdopen() failed: %s"),
751 g_strerror (save_errno));
752 g_free (display_filename);
757 retval = get_contents_stdio (display_filename, f, contents, length, error);
758 g_free (display_filename);
764 #else /* G_OS_WIN32 */
767 get_contents_win32 (const gchar *filename,
774 gchar *display_filename = g_filename_display_name (filename);
777 f = g_fopen (filename, "rb");
784 g_file_error_from_errno (save_errno),
785 _("Failed to open file '%s': %s"),
787 g_strerror (save_errno));
788 g_free (display_filename);
793 retval = get_contents_stdio (display_filename, f, contents, length, error);
794 g_free (display_filename);
802 * g_file_get_contents:
803 * @filename: name of a file to read contents from, in the GLib file name encoding
804 * @contents: location to store an allocated string, use g_free() to free
805 * the returned string
806 * @length: location to store length in bytes of the contents, or %NULL
807 * @error: return location for a #GError, or %NULL
809 * Reads an entire file into allocated memory, with good error
812 * If the call was successful, it returns %TRUE and sets @contents to the file
813 * contents and @length to the length of the file contents in bytes. The string
814 * stored in @contents will be nul-terminated, so for text files you can pass
815 * %NULL for the @length argument. If the call was not successful, it returns
816 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
817 * codes are those in the #GFileError enumeration. In the error case,
818 * @contents is set to %NULL and @length is set to zero.
820 * Return value: %TRUE on success, %FALSE if an error occurred
823 g_file_get_contents (const gchar *filename,
828 g_return_val_if_fail (filename != NULL, FALSE);
829 g_return_val_if_fail (contents != NULL, FALSE);
836 return get_contents_win32 (filename, contents, length, error);
838 return get_contents_posix (filename, contents, length, error);
843 rename_file (const char *old_name,
844 const char *new_name,
848 if (g_rename (old_name, new_name) == -1)
850 int save_errno = errno;
851 gchar *display_old_name = g_filename_display_name (old_name);
852 gchar *display_new_name = g_filename_display_name (new_name);
856 g_file_error_from_errno (save_errno),
857 _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
860 g_strerror (save_errno));
862 g_free (display_old_name);
863 g_free (display_new_name);
872 write_to_temp_file (const gchar *contents,
874 const gchar *dest_file,
886 tmp_name = g_strdup_printf ("%s.XXXXXX", dest_file);
889 fd = g_mkstemp_full (tmp_name, O_RDWR | O_BINARY, 0666);
892 display_name = g_filename_display_name (tmp_name);
898 g_file_error_from_errno (save_errno),
899 _("Failed to create file '%s': %s"),
900 display_name, g_strerror (save_errno));
906 file = fdopen (fd, "wb");
912 g_file_error_from_errno (save_errno),
913 _("Failed to open file '%s' for writing: fdopen() failed: %s"),
915 g_strerror (save_errno));
929 n_written = fwrite (contents, 1, length, file);
931 if (n_written < length)
937 g_file_error_from_errno (save_errno),
938 _("Failed to write file '%s': fwrite() failed: %s"),
940 g_strerror (save_errno));
950 if (fflush (file) != 0)
956 g_file_error_from_errno (save_errno),
957 _("Failed to write file '%s': fflush() failed: %s"),
959 g_strerror (save_errno));
971 /* If the final destination exists and is > 0 bytes, we want to sync the
972 * newly written file to ensure the data is on disk when we rename over
973 * the destination. Otherwise if we get a system crash we can lose both
974 * the new and the old file on some filesystems. (I.E. those that don't
975 * guarantee the data is written to the disk before the metadata.)
977 if (g_lstat (dest_file, &statbuf) == 0 &&
978 statbuf.st_size > 0 &&
979 fsync (fileno (file)) != 0)
985 g_file_error_from_errno (save_errno),
986 _("Failed to write file '%s': fsync() failed: %s"),
988 g_strerror (save_errno));
998 if (fclose (file) == EOF)
1004 g_file_error_from_errno (save_errno),
1005 _("Failed to close file '%s': fclose() failed: %s"),
1007 g_strerror (save_errno));
1009 g_unlink (tmp_name);
1014 retval = g_strdup (tmp_name);
1018 g_free (display_name);
1024 * g_file_set_contents:
1025 * @filename: name of a file to write @contents to, in the GLib file name
1027 * @contents: string to write to the file
1028 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1029 * @error: return location for a #GError, or %NULL
1031 * Writes all of @contents to a file named @filename, with good error checking.
1032 * If a file called @filename already exists it will be overwritten.
1034 * This write is atomic in the sense that it is first written to a temporary
1035 * file which is then renamed to the final name. Notes:
1038 * On Unix, if @filename already exists hard links to @filename will break.
1039 * Also since the file is recreated, existing permissions, access control
1040 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1041 * the link itself will be replaced, not the linked file.
1044 * On Windows renaming a file will not remove an existing file with the
1045 * new name, so on Windows there is a race condition between the existing
1046 * file being removed and the temporary file being renamed.
1049 * On Windows there is no way to remove a file that is open to some
1050 * process, or mapped into memory. Thus, this function will fail if
1051 * @filename already exists and is open.
1055 * If the call was sucessful, it returns %TRUE. If the call was not successful,
1056 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1057 * Possible error codes are those in the #GFileError enumeration.
1059 * Return value: %TRUE on success, %FALSE if an error occurred
1064 g_file_set_contents (const gchar *filename,
1065 const gchar *contents,
1069 gchar *tmp_filename;
1071 GError *rename_error = NULL;
1073 g_return_val_if_fail (filename != NULL, FALSE);
1074 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1075 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1076 g_return_val_if_fail (length >= -1, FALSE);
1079 length = strlen (contents);
1081 tmp_filename = write_to_temp_file (contents, length, filename, error);
1089 if (!rename_file (tmp_filename, filename, &rename_error))
1093 g_unlink (tmp_filename);
1094 g_propagate_error (error, rename_error);
1098 #else /* G_OS_WIN32 */
1100 /* Renaming failed, but on Windows this may just mean
1101 * the file already exists. So if the target file
1102 * exists, try deleting it and do the rename again.
1104 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1106 g_unlink (tmp_filename);
1107 g_propagate_error (error, rename_error);
1112 g_error_free (rename_error);
1114 if (g_unlink (filename) == -1)
1116 gchar *display_filename = g_filename_display_name (filename);
1118 int save_errno = errno;
1122 g_file_error_from_errno (save_errno),
1123 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1125 g_strerror (save_errno));
1127 g_free (display_filename);
1128 g_unlink (tmp_filename);
1133 if (!rename_file (tmp_filename, filename, error))
1135 g_unlink (tmp_filename);
1146 g_free (tmp_filename);
1152 * @tmpl: template filename
1153 * @flags: flags to pass to an open() call in addition to O_EXCL and
1154 * O_CREAT, which are passed automatically
1155 * @mode: permissios to create the temporary file with
1157 * Opens a temporary file. See the mkstemp() documentation
1158 * on most UNIX-like systems.
1160 * The parameter is a string that should follow the rules for
1161 * mkstemp() templates, i.e. contain the string "XXXXXX".
1162 * g_mkstemp_full() is slightly more flexible than mkstemp()
1163 * in that the sequence does not have to occur at the very end of the
1164 * template and you can pass a @mode and additional @flags. The X
1165 * string will be modified to form the name of a file that didn't exist.
1166 * The string should be in the GLib file name encoding. Most importantly,
1167 * on Windows it should be in UTF-8.
1169 * Return value: A file handle (as from open()) to the file
1170 * opened for reading and writing. The file handle should be
1171 * closed with close(). In case of errors, -1 is returned.
1176 * g_mkstemp_full based on the mkstemp implementation from the GNU C library.
1177 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1180 g_mkstemp_full (gchar *tmpl,
1186 static const char letters[] =
1187 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1188 static const int NLETTERS = sizeof (letters) - 1;
1191 static int counter = 0;
1193 g_return_val_if_fail (tmpl != NULL, -1);
1196 /* find the last occurrence of "XXXXXX" */
1197 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1199 if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1205 /* Get some more or less random data. */
1206 g_get_current_time (&tv);
1207 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1209 for (count = 0; count < 100; value += 7777, ++count)
1213 /* Fill in the random bits. */
1214 XXXXXX[0] = letters[v % NLETTERS];
1216 XXXXXX[1] = letters[v % NLETTERS];
1218 XXXXXX[2] = letters[v % NLETTERS];
1220 XXXXXX[3] = letters[v % NLETTERS];
1222 XXXXXX[4] = letters[v % NLETTERS];
1224 XXXXXX[5] = letters[v % NLETTERS];
1226 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1227 fd = g_open (tmpl, flags | O_CREAT | O_EXCL, mode);
1231 else if (errno != EEXIST)
1232 /* Any other error will apply also to other names we might
1233 * try, and there are 2^32 or so of them, so give up now.
1238 /* We got out of the loop because we ran out of combinations to try. */
1245 * @tmpl: template filename
1247 * Opens a temporary file. See the mkstemp() documentation
1248 * on most UNIX-like systems.
1250 * The parameter is a string that should follow the rules for
1251 * mkstemp() templates, i.e. contain the string "XXXXXX".
1252 * g_mkstemp() is slightly more flexible than mkstemp()
1253 * in that the sequence does not have to occur at the very end of the
1254 * template. The X string will
1255 * be modified to form the name of a file that didn't exist.
1256 * The string should be in the GLib file name encoding. Most importantly,
1257 * on Windows it should be in UTF-8.
1259 * Return value: A file handle (as from open()) to the file
1260 * opened for reading and writing. The file is opened in binary mode
1261 * on platforms where there is a difference. The file handle should be
1262 * closed with close(). In case of errors, -1 is returned.
1265 g_mkstemp (gchar *tmpl)
1267 return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1272 * @tmpl: Template for file name, as in g_mkstemp(), basename only,
1273 * or %NULL, to a default template
1274 * @name_used: location to store actual name used, or %NULL
1275 * @error: return location for a #GError
1277 * Opens a file for writing in the preferred directory for temporary
1278 * files (as returned by g_get_tmp_dir()).
1280 * @tmpl should be a string in the GLib file name encoding containing
1281 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1282 * However, unlike these functions, the template should only be a
1283 * basename, no directory components are allowed. If template is
1284 * %NULL, a default template is used.
1286 * Note that in contrast to g_mkstemp() (and mkstemp())
1287 * @tmpl is not modified, and might thus be a read-only literal string.
1289 * The actual name used is returned in @name_used if non-%NULL. This
1290 * string should be freed with g_free() when not needed any longer.
1291 * The returned name is in the GLib file name encoding.
1293 * Return value: A file handle (as from open()) to
1294 * the file opened for reading and writing. The file is opened in binary
1295 * mode on platforms where there is a difference. The file handle should be
1296 * closed with close(). In case of errors, -1 is returned
1297 * and @error will be set.
1300 g_file_open_tmp (const gchar *tmpl,
1313 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1315 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1319 gchar *display_tmpl = g_filename_display_name (tmpl);
1326 G_FILE_ERROR_FAILED,
1327 _("Template '%s' invalid, should not contain a '%s'"),
1329 g_free (display_tmpl);
1334 if (strstr (tmpl, "XXXXXX") == NULL)
1336 gchar *display_tmpl = g_filename_display_name (tmpl);
1339 G_FILE_ERROR_FAILED,
1340 _("Template '%s' doesn't contain XXXXXX"),
1342 g_free (display_tmpl);
1346 tmpdir = g_get_tmp_dir ();
1348 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1351 sep = G_DIR_SEPARATOR_S;
1353 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1355 retval = g_mkstemp (fulltemplate);
1359 int save_errno = errno;
1360 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1364 g_file_error_from_errno (save_errno),
1365 _("Failed to create file '%s': %s"),
1366 display_fulltemplate, g_strerror (save_errno));
1367 g_free (display_fulltemplate);
1368 g_free (fulltemplate);
1373 *name_used = fulltemplate;
1375 g_free (fulltemplate);
1381 g_build_path_va (const gchar *separator,
1382 const gchar *first_element,
1387 gint separator_len = strlen (separator);
1388 gboolean is_first = TRUE;
1389 gboolean have_leading = FALSE;
1390 const gchar *single_element = NULL;
1391 const gchar *next_element;
1392 const gchar *last_trailing = NULL;
1395 result = g_string_new (NULL);
1398 next_element = str_array[i++];
1400 next_element = first_element;
1404 const gchar *element;
1410 element = next_element;
1412 next_element = str_array[i++];
1414 next_element = va_arg (*args, gchar *);
1419 /* Ignore empty elements */
1427 while (strncmp (start, separator, separator_len) == 0)
1428 start += separator_len;
1431 end = start + strlen (start);
1435 while (end >= start + separator_len &&
1436 strncmp (end - separator_len, separator, separator_len) == 0)
1437 end -= separator_len;
1439 last_trailing = end;
1440 while (last_trailing >= element + separator_len &&
1441 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1442 last_trailing -= separator_len;
1446 /* If the leading and trailing separator strings are in the
1447 * same element and overlap, the result is exactly that element
1449 if (last_trailing <= start)
1450 single_element = element;
1452 g_string_append_len (result, element, start - element);
1453 have_leading = TRUE;
1456 single_element = NULL;
1463 g_string_append (result, separator);
1465 g_string_append_len (result, start, end - start);
1471 g_string_free (result, TRUE);
1472 return g_strdup (single_element);
1477 g_string_append (result, last_trailing);
1479 return g_string_free (result, FALSE);
1485 * @separator: a string used to separator the elements of the path.
1486 * @args: %NULL-terminated array of strings containing the path elements.
1488 * Behaves exactly like g_build_path(), but takes the path elements
1489 * as a string array, instead of varargs. This function is mainly
1490 * meant for language bindings.
1492 * Return value: a newly-allocated string that must be freed with g_free().
1497 g_build_pathv (const gchar *separator,
1503 return g_build_path_va (separator, NULL, NULL, args);
1509 * @separator: a string used to separator the elements of the path.
1510 * @first_element: the first element in the path
1511 * @Varargs: remaining elements in path, terminated by %NULL
1513 * Creates a path from a series of elements using @separator as the
1514 * separator between elements. At the boundary between two elements,
1515 * any trailing occurrences of separator in the first element, or
1516 * leading occurrences of separator in the second element are removed
1517 * and exactly one copy of the separator is inserted.
1519 * Empty elements are ignored.
1521 * The number of leading copies of the separator on the result is
1522 * the same as the number of leading copies of the separator on
1523 * the first non-empty element.
1525 * The number of trailing copies of the separator on the result is
1526 * the same as the number of trailing copies of the separator on
1527 * the last non-empty element. (Determination of the number of
1528 * trailing copies is done without stripping leading copies, so
1529 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1530 * has 1 trailing copy.)
1532 * However, if there is only a single non-empty element, and there
1533 * are no characters in that element not part of the leading or
1534 * trailing separators, then the result is exactly the original value
1537 * Other than for determination of the number of leading and trailing
1538 * copies of the separator, elements consisting only of copies
1539 * of the separator are ignored.
1541 * Return value: a newly-allocated string that must be freed with g_free().
1544 g_build_path (const gchar *separator,
1545 const gchar *first_element,
1551 g_return_val_if_fail (separator != NULL, NULL);
1553 va_start (args, first_element);
1554 str = g_build_path_va (separator, first_element, &args, NULL);
1563 g_build_pathname_va (const gchar *first_element,
1567 /* Code copied from g_build_pathv(), and modified to use two
1568 * alternative single-character separators.
1571 gboolean is_first = TRUE;
1572 gboolean have_leading = FALSE;
1573 const gchar *single_element = NULL;
1574 const gchar *next_element;
1575 const gchar *last_trailing = NULL;
1576 gchar current_separator = '\\';
1579 result = g_string_new (NULL);
1582 next_element = str_array[i++];
1584 next_element = first_element;
1588 const gchar *element;
1594 element = next_element;
1596 next_element = str_array[i++];
1598 next_element = va_arg (*args, gchar *);
1603 /* Ignore empty elements */
1612 (*start == '\\' || *start == '/'))
1614 current_separator = *start;
1619 end = start + strlen (start);
1623 while (end >= start + 1 &&
1624 (end[-1] == '\\' || end[-1] == '/'))
1626 current_separator = end[-1];
1630 last_trailing = end;
1631 while (last_trailing >= element + 1 &&
1632 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1637 /* If the leading and trailing separator strings are in the
1638 * same element and overlap, the result is exactly that element
1640 if (last_trailing <= start)
1641 single_element = element;
1643 g_string_append_len (result, element, start - element);
1644 have_leading = TRUE;
1647 single_element = NULL;
1654 g_string_append_len (result, ¤t_separator, 1);
1656 g_string_append_len (result, start, end - start);
1662 g_string_free (result, TRUE);
1663 return g_strdup (single_element);
1668 g_string_append (result, last_trailing);
1670 return g_string_free (result, FALSE);
1677 * g_build_filenamev:
1678 * @args: %NULL-terminated array of strings containing the path elements.
1680 * Behaves exactly like g_build_filename(), but takes the path elements
1681 * as a string array, instead of varargs. This function is mainly
1682 * meant for language bindings.
1684 * Return value: a newly-allocated string that must be freed with g_free().
1689 g_build_filenamev (gchar **args)
1694 str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1696 str = g_build_pathname_va (NULL, NULL, args);
1704 * @first_element: the first element in the path
1705 * @Varargs: remaining elements in path, terminated by %NULL
1707 * Creates a filename from a series of elements using the correct
1708 * separator for filenames.
1710 * On Unix, this function behaves identically to <literal>g_build_path
1711 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1713 * On Windows, it takes into account that either the backslash
1714 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1715 * as separator in filenames, but otherwise behaves as on Unix. When
1716 * file pathname separators need to be inserted, the one that last
1717 * previously occurred in the parameters (reading from left to right)
1720 * No attempt is made to force the resulting filename to be an absolute
1721 * path. If the first element is a relative path, the result will
1722 * be a relative path.
1724 * Return value: a newly-allocated string that must be freed with g_free().
1727 g_build_filename (const gchar *first_element,
1733 va_start (args, first_element);
1735 str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1737 str = g_build_pathname_va (first_element, &args, NULL);
1744 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
1745 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
1746 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
1747 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
1748 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
1749 #define EXABYTE_FACTOR (PETABYTE_FACTOR * KILOBYTE_FACTOR)
1752 * g_format_size_for_display:
1753 * @size: a size in bytes.
1755 * Formats a size (for example the size of a file) into a human readable string.
1756 * Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed
1757 * rounded to the nearest tenth. E.g. the file size 3292528 bytes will be
1758 * converted into the string "3.1 MB".
1760 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
1762 * This string should be freed with g_free() when not needed any longer.
1764 * Returns: a newly-allocated formatted string containing a human readable
1770 g_format_size_for_display (goffset size)
1772 if (size < (goffset) KILOBYTE_FACTOR)
1773 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
1776 gdouble displayed_size;
1778 if (size < (goffset) MEGABYTE_FACTOR)
1780 displayed_size = (gdouble) size / (gdouble) KILOBYTE_FACTOR;
1781 return g_strdup_printf (_("%.1f KB"), displayed_size);
1783 else if (size < (goffset) GIGABYTE_FACTOR)
1785 displayed_size = (gdouble) size / (gdouble) MEGABYTE_FACTOR;
1786 return g_strdup_printf (_("%.1f MB"), displayed_size);
1788 else if (size < (goffset) TERABYTE_FACTOR)
1790 displayed_size = (gdouble) size / (gdouble) GIGABYTE_FACTOR;
1791 return g_strdup_printf (_("%.1f GB"), displayed_size);
1793 else if (size < (goffset) PETABYTE_FACTOR)
1795 displayed_size = (gdouble) size / (gdouble) TERABYTE_FACTOR;
1796 return g_strdup_printf (_("%.1f TB"), displayed_size);
1798 else if (size < (goffset) EXABYTE_FACTOR)
1800 displayed_size = (gdouble) size / (gdouble) PETABYTE_FACTOR;
1801 return g_strdup_printf (_("%.1f PB"), displayed_size);
1805 displayed_size = (gdouble) size / (gdouble) EXABYTE_FACTOR;
1806 return g_strdup_printf (_("%.1f EB"), displayed_size);
1814 * @filename: the symbolic link
1815 * @error: return location for a #GError
1817 * Reads the contents of the symbolic link @filename like the POSIX
1818 * readlink() function. The returned string is in the encoding used
1819 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1821 * Returns: A newly-allocated string with the contents of the symbolic link,
1822 * or %NULL if an error occurred.
1827 g_file_read_link (const gchar *filename,
1830 #ifdef HAVE_READLINK
1836 buffer = g_malloc (size);
1840 read_size = readlink (filename, buffer, size);
1841 if (read_size < 0) {
1842 int save_errno = errno;
1843 gchar *display_filename = g_filename_display_name (filename);
1848 g_file_error_from_errno (save_errno),
1849 _("Failed to read the symbolic link '%s': %s"),
1851 g_strerror (save_errno));
1852 g_free (display_filename);
1857 if (read_size < size)
1859 buffer[read_size] = 0;
1864 buffer = g_realloc (buffer, size);
1867 g_set_error_literal (error,
1870 _("Symbolic links not supported"));
1876 /* NOTE : Keep this part last to ensure nothing in this file uses the
1877 * below binary compatibility versions.
1879 #if defined (G_OS_WIN32) && !defined (_WIN64)
1881 /* Binary compatibility versions. Will be called by code compiled
1882 * against quite old (pre-2.8, I think) headers only, not from more
1883 * recently compiled code.
1889 g_file_test (const gchar *filename,
1892 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
1895 if (utf8_filename == NULL)
1898 retval = g_file_test_utf8 (utf8_filename, test);
1900 g_free (utf8_filename);
1905 #undef g_file_get_contents
1908 g_file_get_contents (const gchar *filename,
1913 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
1916 if (utf8_filename == NULL)
1919 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
1921 g_free (utf8_filename);
1929 g_mkstemp (gchar *tmpl)
1933 static const char letters[] =
1934 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1935 static const int NLETTERS = sizeof (letters) - 1;
1938 static int counter = 0;
1940 /* find the last occurrence of 'XXXXXX' */
1941 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1949 /* Get some more or less random data. */
1950 g_get_current_time (&tv);
1951 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1953 for (count = 0; count < 100; value += 7777, ++count)
1957 /* Fill in the random bits. */
1958 XXXXXX[0] = letters[v % NLETTERS];
1960 XXXXXX[1] = letters[v % NLETTERS];
1962 XXXXXX[2] = letters[v % NLETTERS];
1964 XXXXXX[3] = letters[v % NLETTERS];
1966 XXXXXX[4] = letters[v % NLETTERS];
1968 XXXXXX[5] = letters[v % NLETTERS];
1970 /* This is the backward compatibility system codepage version,
1971 * thus use normal open().
1973 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1977 else if (errno != EEXIST)
1978 /* Any other error will apply also to other names we might
1979 * try, and there are 2^32 or so of them, so give up now.
1984 /* We got out of the loop because we ran out of combinations to try. */
1989 #undef g_file_open_tmp
1992 g_file_open_tmp (const gchar *tmpl,
1996 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1997 gchar *utf8_name_used;
2000 if (utf8_tmpl == NULL)
2003 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
2009 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
2011 g_free (utf8_name_used);