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 */
58 * g_mkdir_with_parents:
59 * @pathname: a pathname in the GLib file name encoding
60 * @mode: permissions to use for newly created directories
62 * Create a directory if it doesn't already exist. Create intermediate
63 * parent directories as needed, too.
65 * Returns: 0 if the directory already exists, or was successfully
66 * created. Returns -1 if an error occurred, with errno set.
71 g_mkdir_with_parents (const gchar *pathname,
76 if (pathname == NULL || *pathname == '\0')
82 fn = g_strdup (pathname);
84 if (g_path_is_absolute (fn))
85 p = (gchar *) g_path_skip_root (fn);
91 while (*p && !G_IS_DIR_SEPARATOR (*p))
99 if (!g_file_test (fn, G_FILE_TEST_EXISTS))
101 if (g_mkdir (fn, mode) == -1)
103 int errno_save = errno;
109 else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
117 *p++ = G_DIR_SEPARATOR;
118 while (*p && G_IS_DIR_SEPARATOR (*p))
131 * @filename: a filename to test in the GLib file name encoding
132 * @test: bitfield of #GFileTest flags
134 * Returns %TRUE if any of the tests in the bitfield @test are
135 * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS |
136 * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists;
137 * the check whether it's a directory doesn't matter since the existence
138 * test is %TRUE. With the current set of available tests, there's no point
139 * passing in more than one test at a time.
141 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
142 * so for a symbolic link to a regular file g_file_test() will return
143 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
145 * Note, that for a dangling symbolic link g_file_test() will return
146 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
148 * You should never use g_file_test() to test whether it is safe
149 * to perform an operation, because there is always the possibility
150 * of the condition changing before you actually perform the operation.
151 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
152 * to know whether it is safe to write to a file without being
153 * tricked into writing into a different location. It doesn't work!
155 * /* DON'T DO THIS */
156 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
158 * fd = g_open (filename, O_WRONLY);
159 * /* write to fd */
163 * Another thing to note is that %G_FILE_TEST_EXISTS and
164 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
165 * system call. This usually doesn't matter, but if your program
166 * is setuid or setgid it means that these tests will give you
167 * the answer for the real user ID and group ID, rather than the
168 * effective user ID and group ID.
170 * On Windows, there are no symlinks, so testing for
171 * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
172 * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
173 * its name indicates that it is executable, checking for well-known
174 * extensions and those listed in the %PATHEXT environment variable.
176 * Return value: whether a test was %TRUE
179 g_file_test (const gchar *filename,
183 /* stuff missing in std vc6 api */
184 # ifndef INVALID_FILE_ATTRIBUTES
185 # define INVALID_FILE_ATTRIBUTES -1
187 # ifndef FILE_ATTRIBUTE_DEVICE
188 # define FILE_ATTRIBUTE_DEVICE 64
191 wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
193 if (wfilename == NULL)
196 attributes = GetFileAttributesW (wfilename);
200 if (attributes == INVALID_FILE_ATTRIBUTES)
203 if (test & G_FILE_TEST_EXISTS)
206 if (test & G_FILE_TEST_IS_REGULAR)
208 if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0)
212 if (test & G_FILE_TEST_IS_DIR)
214 if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
218 /* "while" so that we can exit this "loop" with a simple "break" */
219 while (test & G_FILE_TEST_IS_EXECUTABLE)
221 const gchar *lastdot = strrchr (filename, '.');
222 const gchar *pathext = NULL, *p;
228 if (_stricmp (lastdot, ".exe") == 0 ||
229 _stricmp (lastdot, ".cmd") == 0 ||
230 _stricmp (lastdot, ".bat") == 0 ||
231 _stricmp (lastdot, ".com") == 0)
234 /* Check if it is one of the types listed in %PATHEXT% */
236 pathext = g_getenv ("PATHEXT");
240 pathext = g_utf8_casefold (pathext, -1);
242 lastdot = g_utf8_casefold (lastdot, -1);
243 extlen = strlen (lastdot);
248 const gchar *q = strchr (p, ';');
251 if (extlen == q - p &&
252 memcmp (lastdot, p, extlen) == 0)
254 g_free ((gchar *) pathext);
255 g_free ((gchar *) lastdot);
264 g_free ((gchar *) pathext);
265 g_free ((gchar *) lastdot);
271 if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
274 if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
279 /* For root, on some POSIX systems, access (filename, X_OK)
280 * will succeed even if no executable bits are set on the
281 * file. We fall through to a stat test to avoid that.
285 test &= ~G_FILE_TEST_IS_EXECUTABLE;
287 if (test & G_FILE_TEST_IS_SYMLINK)
291 if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
295 if (test & (G_FILE_TEST_IS_REGULAR |
297 G_FILE_TEST_IS_EXECUTABLE))
301 if (stat (filename, &s) == 0)
303 if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
306 if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
309 /* The extra test for root when access (file, X_OK) succeeds.
311 if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
312 ((s.st_mode & S_IXOTH) ||
313 (s.st_mode & S_IXUSR) ||
314 (s.st_mode & S_IXGRP)))
324 g_file_error_quark (void)
326 return g_quark_from_static_string ("g-file-error-quark");
330 * g_file_error_from_errno:
331 * @err_no: an "errno" value
333 * Gets a #GFileError constant based on the passed-in @errno.
334 * For example, if you pass in %EEXIST this function returns
335 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
336 * assume that all #GFileError values will exist.
338 * Normally a #GFileError value goes into a #GError returned
339 * from a function that manipulates files. So you would use
340 * g_file_error_from_errno() when constructing a #GError.
342 * Return value: #GFileError corresponding to the given @errno
345 g_file_error_from_errno (gint err_no)
351 return G_FILE_ERROR_EXIST;
357 return G_FILE_ERROR_ISDIR;
363 return G_FILE_ERROR_ACCES;
369 return G_FILE_ERROR_NAMETOOLONG;
375 return G_FILE_ERROR_NOENT;
381 return G_FILE_ERROR_NOTDIR;
387 return G_FILE_ERROR_NXIO;
393 return G_FILE_ERROR_NODEV;
399 return G_FILE_ERROR_ROFS;
405 return G_FILE_ERROR_TXTBSY;
411 return G_FILE_ERROR_FAULT;
417 return G_FILE_ERROR_LOOP;
423 return G_FILE_ERROR_NOSPC;
429 return G_FILE_ERROR_NOMEM;
435 return G_FILE_ERROR_MFILE;
441 return G_FILE_ERROR_NFILE;
447 return G_FILE_ERROR_BADF;
453 return G_FILE_ERROR_INVAL;
459 return G_FILE_ERROR_PIPE;
465 return G_FILE_ERROR_AGAIN;
471 return G_FILE_ERROR_INTR;
477 return G_FILE_ERROR_IO;
483 return G_FILE_ERROR_PERM;
489 return G_FILE_ERROR_NOSYS;
494 return G_FILE_ERROR_FAILED;
500 get_contents_stdio (const gchar *display_filename,
509 gsize total_bytes = 0;
510 gsize total_allocated = 0;
513 g_assert (f != NULL);
519 bytes = fread (buf, 1, sizeof (buf), f);
522 while ((total_bytes + bytes + 1) > total_allocated)
525 total_allocated *= 2;
527 total_allocated = MIN (bytes + 1, sizeof (buf));
529 tmp = g_try_realloc (str, total_allocated);
536 _("Could not allocate %lu bytes to read file \"%s\""),
537 (gulong) total_allocated,
550 g_file_error_from_errno (save_errno),
551 _("Error reading file '%s': %s"),
553 g_strerror (save_errno));
558 memcpy (str + total_bytes, buf, bytes);
560 if (total_bytes + bytes < total_bytes)
565 _("File \"%s\" is too large"),
571 total_bytes += bytes;
576 if (total_allocated == 0)
578 str = g_new (gchar, 1);
582 str[total_bytes] = '\0';
585 *length = total_bytes;
602 get_contents_regfile (const gchar *display_filename,
603 struct stat *stat_buf,
614 size = stat_buf->st_size;
616 alloc_size = size + 1;
617 buf = g_try_malloc (alloc_size);
624 _("Could not allocate %lu bytes to read file \"%s\""),
632 while (bytes_read < size)
636 rc = read (fd, buf + bytes_read, size - bytes_read);
642 int save_errno = errno;
647 g_file_error_from_errno (save_errno),
648 _("Failed to read from file '%s': %s"),
650 g_strerror (save_errno));
661 buf[bytes_read] = '\0';
664 *length = bytes_read;
680 get_contents_posix (const gchar *filename,
685 struct stat stat_buf;
687 gchar *display_filename = g_filename_display_name (filename);
689 /* O_BINARY useful on Cygwin */
690 fd = open (filename, O_RDONLY|O_BINARY);
694 int save_errno = errno;
698 g_file_error_from_errno (save_errno),
699 _("Failed to open file '%s': %s"),
701 g_strerror (save_errno));
702 g_free (display_filename);
707 /* I don't think this will ever fail, aside from ENOMEM, but. */
708 if (fstat (fd, &stat_buf) < 0)
710 int save_errno = errno;
715 g_file_error_from_errno (save_errno),
716 _("Failed to get attributes of file '%s': fstat() failed: %s"),
718 g_strerror (save_errno));
719 g_free (display_filename);
724 if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
726 gboolean retval = get_contents_regfile (display_filename,
732 g_free (display_filename);
741 f = fdopen (fd, "r");
745 int save_errno = errno;
749 g_file_error_from_errno (save_errno),
750 _("Failed to open file '%s': fdopen() failed: %s"),
752 g_strerror (save_errno));
753 g_free (display_filename);
758 retval = get_contents_stdio (display_filename, f, contents, length, error);
759 g_free (display_filename);
765 #else /* G_OS_WIN32 */
768 get_contents_win32 (const gchar *filename,
775 gchar *display_filename = g_filename_display_name (filename);
778 f = g_fopen (filename, "rb");
785 g_file_error_from_errno (save_errno),
786 _("Failed to open file '%s': %s"),
788 g_strerror (save_errno));
789 g_free (display_filename);
794 retval = get_contents_stdio (display_filename, f, contents, length, error);
795 g_free (display_filename);
803 * g_file_get_contents:
804 * @filename: name of a file to read contents from, in the GLib file name encoding
805 * @contents: location to store an allocated string, use g_free() to free
806 * the returned string
807 * @length: location to store length in bytes of the contents, or %NULL
808 * @error: return location for a #GError, or %NULL
810 * Reads an entire file into allocated memory, with good error
813 * If the call was successful, it returns %TRUE and sets @contents to the file
814 * contents and @length to the length of the file contents in bytes. The string
815 * stored in @contents will be nul-terminated, so for text files you can pass
816 * %NULL for the @length argument. If the call was not successful, it returns
817 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
818 * codes are those in the #GFileError enumeration. In the error case,
819 * @contents is set to %NULL and @length is set to zero.
821 * Return value: %TRUE on success, %FALSE if an error occurred
824 g_file_get_contents (const gchar *filename,
829 g_return_val_if_fail (filename != NULL, FALSE);
830 g_return_val_if_fail (contents != NULL, FALSE);
837 return get_contents_win32 (filename, contents, length, error);
839 return get_contents_posix (filename, contents, length, error);
844 rename_file (const char *old_name,
845 const char *new_name,
849 if (g_rename (old_name, new_name) == -1)
851 int save_errno = errno;
852 gchar *display_old_name = g_filename_display_name (old_name);
853 gchar *display_new_name = g_filename_display_name (new_name);
857 g_file_error_from_errno (save_errno),
858 _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
861 g_strerror (save_errno));
863 g_free (display_old_name);
864 g_free (display_new_name);
873 write_to_temp_file (const gchar *contents,
875 const gchar *dest_file,
887 tmp_name = g_strdup_printf ("%s.XXXXXX", dest_file);
890 fd = g_mkstemp_full (tmp_name, O_RDWR | O_BINARY, 0666);
893 display_name = g_filename_display_name (tmp_name);
899 g_file_error_from_errno (save_errno),
900 _("Failed to create file '%s': %s"),
901 display_name, g_strerror (save_errno));
907 file = fdopen (fd, "wb");
913 g_file_error_from_errno (save_errno),
914 _("Failed to open file '%s' for writing: fdopen() failed: %s"),
916 g_strerror (save_errno));
930 n_written = fwrite (contents, 1, length, file);
932 if (n_written < length)
938 g_file_error_from_errno (save_errno),
939 _("Failed to write file '%s': fwrite() failed: %s"),
941 g_strerror (save_errno));
951 if (fflush (file) != 0)
957 g_file_error_from_errno (save_errno),
958 _("Failed to write file '%s': fflush() failed: %s"),
960 g_strerror (save_errno));
972 /* If the final destination exists and is > 0 bytes, we want to sync the
973 * newly written file to ensure the data is on disk when we rename over
974 * the destination. Otherwise if we get a system crash we can lose both
975 * the new and the old file on some filesystems. (I.E. those that don't
976 * guarantee the data is written to the disk before the metadata.)
978 if (g_lstat (dest_file, &statbuf) == 0 &&
979 statbuf.st_size > 0 &&
980 fsync (fileno (file)) != 0)
986 g_file_error_from_errno (save_errno),
987 _("Failed to write file '%s': fsync() failed: %s"),
989 g_strerror (save_errno));
999 if (fclose (file) == EOF)
1005 g_file_error_from_errno (save_errno),
1006 _("Failed to close file '%s': fclose() failed: %s"),
1008 g_strerror (save_errno));
1010 g_unlink (tmp_name);
1015 retval = g_strdup (tmp_name);
1019 g_free (display_name);
1025 * g_file_set_contents:
1026 * @filename: name of a file to write @contents to, in the GLib file name
1028 * @contents: string to write to the file
1029 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1030 * @error: return location for a #GError, or %NULL
1032 * Writes all of @contents to a file named @filename, with good error checking.
1033 * If a file called @filename already exists it will be overwritten.
1035 * This write is atomic in the sense that it is first written to a temporary
1036 * file which is then renamed to the final name. Notes:
1039 * On Unix, if @filename already exists hard links to @filename will break.
1040 * Also since the file is recreated, existing permissions, access control
1041 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1042 * the link itself will be replaced, not the linked file.
1045 * On Windows renaming a file will not remove an existing file with the
1046 * new name, so on Windows there is a race condition between the existing
1047 * file being removed and the temporary file being renamed.
1050 * On Windows there is no way to remove a file that is open to some
1051 * process, or mapped into memory. Thus, this function will fail if
1052 * @filename already exists and is open.
1056 * If the call was sucessful, it returns %TRUE. If the call was not successful,
1057 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1058 * Possible error codes are those in the #GFileError enumeration.
1060 * Return value: %TRUE on success, %FALSE if an error occurred
1065 g_file_set_contents (const gchar *filename,
1066 const gchar *contents,
1070 gchar *tmp_filename;
1072 GError *rename_error = NULL;
1074 g_return_val_if_fail (filename != NULL, FALSE);
1075 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1076 g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1077 g_return_val_if_fail (length >= -1, FALSE);
1080 length = strlen (contents);
1082 tmp_filename = write_to_temp_file (contents, length, filename, error);
1090 if (!rename_file (tmp_filename, filename, &rename_error))
1094 g_unlink (tmp_filename);
1095 g_propagate_error (error, rename_error);
1099 #else /* G_OS_WIN32 */
1101 /* Renaming failed, but on Windows this may just mean
1102 * the file already exists. So if the target file
1103 * exists, try deleting it and do the rename again.
1105 if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1107 g_unlink (tmp_filename);
1108 g_propagate_error (error, rename_error);
1113 g_error_free (rename_error);
1115 if (g_unlink (filename) == -1)
1117 gchar *display_filename = g_filename_display_name (filename);
1119 int save_errno = errno;
1123 g_file_error_from_errno (save_errno),
1124 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1126 g_strerror (save_errno));
1128 g_free (display_filename);
1129 g_unlink (tmp_filename);
1134 if (!rename_file (tmp_filename, filename, error))
1136 g_unlink (tmp_filename);
1147 g_free (tmp_filename);
1153 * @tmpl: template filename
1154 * @flags: flags to pass to an open() call in addition to O_EXCL and
1155 * O_CREAT, which are passed automatically
1156 * @mode: permissios to create the temporary file with
1158 * Opens a temporary file. See the mkstemp() documentation
1159 * on most UNIX-like systems.
1161 * The parameter is a string that should follow the rules for
1162 * mkstemp() templates, i.e. contain the string "XXXXXX".
1163 * g_mkstemp_full() is slightly more flexible than mkstemp()
1164 * in that the sequence does not have to occur at the very end of the
1165 * template and you can pass a @mode and additional @flags. The X
1166 * string will be modified to form the name of a file that didn't exist.
1167 * The string should be in the GLib file name encoding. Most importantly,
1168 * on Windows it should be in UTF-8.
1170 * Return value: A file handle (as from open()) to the file
1171 * opened for reading and writing. The file handle should be
1172 * closed with close(). In case of errors, -1 is returned.
1177 * g_mkstemp_full based on the mkstemp implementation from the GNU C library.
1178 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1181 g_mkstemp_full (gchar *tmpl,
1187 static const char letters[] =
1188 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1189 static const int NLETTERS = sizeof (letters) - 1;
1192 static int counter = 0;
1194 g_return_val_if_fail (tmpl != NULL, -1);
1197 /* find the last occurrence of "XXXXXX" */
1198 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1200 if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1206 /* Get some more or less random data. */
1207 g_get_current_time (&tv);
1208 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1210 for (count = 0; count < 100; value += 7777, ++count)
1214 /* Fill in the random bits. */
1215 XXXXXX[0] = letters[v % NLETTERS];
1217 XXXXXX[1] = letters[v % NLETTERS];
1219 XXXXXX[2] = letters[v % NLETTERS];
1221 XXXXXX[3] = letters[v % NLETTERS];
1223 XXXXXX[4] = letters[v % NLETTERS];
1225 XXXXXX[5] = letters[v % NLETTERS];
1227 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1228 fd = g_open (tmpl, flags | O_CREAT | O_EXCL, mode);
1232 else if (errno != EEXIST)
1233 /* Any other error will apply also to other names we might
1234 * try, and there are 2^32 or so of them, so give up now.
1239 /* We got out of the loop because we ran out of combinations to try. */
1246 * @tmpl: template filename
1248 * Opens a temporary file. See the mkstemp() documentation
1249 * on most UNIX-like systems.
1251 * The parameter is a string that should follow the rules for
1252 * mkstemp() templates, i.e. contain the string "XXXXXX".
1253 * g_mkstemp() is slightly more flexible than mkstemp()
1254 * in that the sequence does not have to occur at the very end of the
1255 * template. The X string will
1256 * be modified to form the name of a file that didn't exist.
1257 * The string should be in the GLib file name encoding. Most importantly,
1258 * on Windows it should be in UTF-8.
1260 * Return value: A file handle (as from open()) to the file
1261 * opened for reading and writing. The file is opened in binary mode
1262 * on platforms where there is a difference. The file handle should be
1263 * closed with close(). In case of errors, -1 is returned.
1266 g_mkstemp (gchar *tmpl)
1268 return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1273 * @tmpl: Template for file name, as in g_mkstemp(), basename only,
1274 * or %NULL, to a default template
1275 * @name_used: location to store actual name used, or %NULL
1276 * @error: return location for a #GError
1278 * Opens a file for writing in the preferred directory for temporary
1279 * files (as returned by g_get_tmp_dir()).
1281 * @tmpl should be a string in the GLib file name encoding containing
1282 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1283 * However, unlike these functions, the template should only be a
1284 * basename, no directory components are allowed. If template is
1285 * %NULL, a default template is used.
1287 * Note that in contrast to g_mkstemp() (and mkstemp())
1288 * @tmpl is not modified, and might thus be a read-only literal string.
1290 * The actual name used is returned in @name_used if non-%NULL. This
1291 * string should be freed with g_free() when not needed any longer.
1292 * The returned name is in the GLib file name encoding.
1294 * Return value: A file handle (as from open()) to
1295 * the file opened for reading and writing. The file is opened in binary
1296 * mode on platforms where there is a difference. The file handle should be
1297 * closed with close(). In case of errors, -1 is returned
1298 * and @error will be set.
1301 g_file_open_tmp (const gchar *tmpl,
1314 if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1316 || (strchr (tmpl, '/') != NULL && (slash = "/"))
1320 gchar *display_tmpl = g_filename_display_name (tmpl);
1327 G_FILE_ERROR_FAILED,
1328 _("Template '%s' invalid, should not contain a '%s'"),
1330 g_free (display_tmpl);
1335 if (strstr (tmpl, "XXXXXX") == NULL)
1337 gchar *display_tmpl = g_filename_display_name (tmpl);
1340 G_FILE_ERROR_FAILED,
1341 _("Template '%s' doesn't contain XXXXXX"),
1343 g_free (display_tmpl);
1347 tmpdir = g_get_tmp_dir ();
1349 if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1352 sep = G_DIR_SEPARATOR_S;
1354 fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1356 retval = g_mkstemp (fulltemplate);
1360 int save_errno = errno;
1361 gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1365 g_file_error_from_errno (save_errno),
1366 _("Failed to create file '%s': %s"),
1367 display_fulltemplate, g_strerror (save_errno));
1368 g_free (display_fulltemplate);
1369 g_free (fulltemplate);
1374 *name_used = fulltemplate;
1376 g_free (fulltemplate);
1382 g_build_path_va (const gchar *separator,
1383 const gchar *first_element,
1388 gint separator_len = strlen (separator);
1389 gboolean is_first = TRUE;
1390 gboolean have_leading = FALSE;
1391 const gchar *single_element = NULL;
1392 const gchar *next_element;
1393 const gchar *last_trailing = NULL;
1396 result = g_string_new (NULL);
1399 next_element = str_array[i++];
1401 next_element = first_element;
1405 const gchar *element;
1411 element = next_element;
1413 next_element = str_array[i++];
1415 next_element = va_arg (*args, gchar *);
1420 /* Ignore empty elements */
1428 while (strncmp (start, separator, separator_len) == 0)
1429 start += separator_len;
1432 end = start + strlen (start);
1436 while (end >= start + separator_len &&
1437 strncmp (end - separator_len, separator, separator_len) == 0)
1438 end -= separator_len;
1440 last_trailing = end;
1441 while (last_trailing >= element + separator_len &&
1442 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1443 last_trailing -= separator_len;
1447 /* If the leading and trailing separator strings are in the
1448 * same element and overlap, the result is exactly that element
1450 if (last_trailing <= start)
1451 single_element = element;
1453 g_string_append_len (result, element, start - element);
1454 have_leading = TRUE;
1457 single_element = NULL;
1464 g_string_append (result, separator);
1466 g_string_append_len (result, start, end - start);
1472 g_string_free (result, TRUE);
1473 return g_strdup (single_element);
1478 g_string_append (result, last_trailing);
1480 return g_string_free (result, FALSE);
1486 * @separator: a string used to separator the elements of the path.
1487 * @args: %NULL-terminated array of strings containing the path elements.
1489 * Behaves exactly like g_build_path(), but takes the path elements
1490 * as a string array, instead of varargs. This function is mainly
1491 * meant for language bindings.
1493 * Return value: a newly-allocated string that must be freed with g_free().
1498 g_build_pathv (const gchar *separator,
1504 return g_build_path_va (separator, NULL, NULL, args);
1510 * @separator: a string used to separator the elements of the path.
1511 * @first_element: the first element in the path
1512 * @Varargs: remaining elements in path, terminated by %NULL
1514 * Creates a path from a series of elements using @separator as the
1515 * separator between elements. At the boundary between two elements,
1516 * any trailing occurrences of separator in the first element, or
1517 * leading occurrences of separator in the second element are removed
1518 * and exactly one copy of the separator is inserted.
1520 * Empty elements are ignored.
1522 * The number of leading copies of the separator on the result is
1523 * the same as the number of leading copies of the separator on
1524 * the first non-empty element.
1526 * The number of trailing copies of the separator on the result is
1527 * the same as the number of trailing copies of the separator on
1528 * the last non-empty element. (Determination of the number of
1529 * trailing copies is done without stripping leading copies, so
1530 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1531 * has 1 trailing copy.)
1533 * However, if there is only a single non-empty element, and there
1534 * are no characters in that element not part of the leading or
1535 * trailing separators, then the result is exactly the original value
1538 * Other than for determination of the number of leading and trailing
1539 * copies of the separator, elements consisting only of copies
1540 * of the separator are ignored.
1542 * Return value: a newly-allocated string that must be freed with g_free().
1545 g_build_path (const gchar *separator,
1546 const gchar *first_element,
1552 g_return_val_if_fail (separator != NULL, NULL);
1554 va_start (args, first_element);
1555 str = g_build_path_va (separator, first_element, &args, NULL);
1564 g_build_pathname_va (const gchar *first_element,
1568 /* Code copied from g_build_pathv(), and modified to use two
1569 * alternative single-character separators.
1572 gboolean is_first = TRUE;
1573 gboolean have_leading = FALSE;
1574 const gchar *single_element = NULL;
1575 const gchar *next_element;
1576 const gchar *last_trailing = NULL;
1577 gchar current_separator = '\\';
1580 result = g_string_new (NULL);
1583 next_element = str_array[i++];
1585 next_element = first_element;
1589 const gchar *element;
1595 element = next_element;
1597 next_element = str_array[i++];
1599 next_element = va_arg (*args, gchar *);
1604 /* Ignore empty elements */
1613 (*start == '\\' || *start == '/'))
1615 current_separator = *start;
1620 end = start + strlen (start);
1624 while (end >= start + 1 &&
1625 (end[-1] == '\\' || end[-1] == '/'))
1627 current_separator = end[-1];
1631 last_trailing = end;
1632 while (last_trailing >= element + 1 &&
1633 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1638 /* If the leading and trailing separator strings are in the
1639 * same element and overlap, the result is exactly that element
1641 if (last_trailing <= start)
1642 single_element = element;
1644 g_string_append_len (result, element, start - element);
1645 have_leading = TRUE;
1648 single_element = NULL;
1655 g_string_append_len (result, ¤t_separator, 1);
1657 g_string_append_len (result, start, end - start);
1663 g_string_free (result, TRUE);
1664 return g_strdup (single_element);
1669 g_string_append (result, last_trailing);
1671 return g_string_free (result, FALSE);
1678 * g_build_filenamev:
1679 * @args: %NULL-terminated array of strings containing the path elements.
1681 * Behaves exactly like g_build_filename(), but takes the path elements
1682 * as a string array, instead of varargs. This function is mainly
1683 * meant for language bindings.
1685 * Return value: a newly-allocated string that must be freed with g_free().
1690 g_build_filenamev (gchar **args)
1695 str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1697 str = g_build_pathname_va (NULL, NULL, args);
1705 * @first_element: the first element in the path
1706 * @Varargs: remaining elements in path, terminated by %NULL
1708 * Creates a filename from a series of elements using the correct
1709 * separator for filenames.
1711 * On Unix, this function behaves identically to <literal>g_build_path
1712 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1714 * On Windows, it takes into account that either the backslash
1715 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1716 * as separator in filenames, but otherwise behaves as on Unix. When
1717 * file pathname separators need to be inserted, the one that last
1718 * previously occurred in the parameters (reading from left to right)
1721 * No attempt is made to force the resulting filename to be an absolute
1722 * path. If the first element is a relative path, the result will
1723 * be a relative path.
1725 * Return value: a newly-allocated string that must be freed with g_free().
1728 g_build_filename (const gchar *first_element,
1734 va_start (args, first_element);
1736 str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
1738 str = g_build_pathname_va (first_element, &args, NULL);
1745 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
1746 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
1747 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
1748 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
1749 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
1750 #define EXABYTE_FACTOR (PETABYTE_FACTOR * KILOBYTE_FACTOR)
1753 * g_format_size_for_display:
1754 * @size: a size in bytes.
1756 * Formats a size (for example the size of a file) into a human readable string.
1757 * Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed
1758 * rounded to the nearest tenth. E.g. the file size 3292528 bytes will be
1759 * converted into the string "3.1 MB".
1761 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
1763 * This string should be freed with g_free() when not needed any longer.
1765 * Returns: a newly-allocated formatted string containing a human readable
1771 g_format_size_for_display (goffset size)
1773 if (size < (goffset) KILOBYTE_FACTOR)
1774 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
1777 gdouble displayed_size;
1779 if (size < (goffset) MEGABYTE_FACTOR)
1781 displayed_size = (gdouble) size / (gdouble) KILOBYTE_FACTOR;
1782 return g_strdup_printf (_("%.1f KB"), displayed_size);
1784 else if (size < (goffset) GIGABYTE_FACTOR)
1786 displayed_size = (gdouble) size / (gdouble) MEGABYTE_FACTOR;
1787 return g_strdup_printf (_("%.1f MB"), displayed_size);
1789 else if (size < (goffset) TERABYTE_FACTOR)
1791 displayed_size = (gdouble) size / (gdouble) GIGABYTE_FACTOR;
1792 return g_strdup_printf (_("%.1f GB"), displayed_size);
1794 else if (size < (goffset) PETABYTE_FACTOR)
1796 displayed_size = (gdouble) size / (gdouble) TERABYTE_FACTOR;
1797 return g_strdup_printf (_("%.1f TB"), displayed_size);
1799 else if (size < (goffset) EXABYTE_FACTOR)
1801 displayed_size = (gdouble) size / (gdouble) PETABYTE_FACTOR;
1802 return g_strdup_printf (_("%.1f PB"), displayed_size);
1806 displayed_size = (gdouble) size / (gdouble) EXABYTE_FACTOR;
1807 return g_strdup_printf (_("%.1f EB"), displayed_size);
1815 * @filename: the symbolic link
1816 * @error: return location for a #GError
1818 * Reads the contents of the symbolic link @filename like the POSIX
1819 * readlink() function. The returned string is in the encoding used
1820 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1822 * Returns: A newly-allocated string with the contents of the symbolic link,
1823 * or %NULL if an error occurred.
1828 g_file_read_link (const gchar *filename,
1831 #ifdef HAVE_READLINK
1837 buffer = g_malloc (size);
1841 read_size = readlink (filename, buffer, size);
1842 if (read_size < 0) {
1843 int save_errno = errno;
1844 gchar *display_filename = g_filename_display_name (filename);
1849 g_file_error_from_errno (save_errno),
1850 _("Failed to read the symbolic link '%s': %s"),
1852 g_strerror (save_errno));
1853 g_free (display_filename);
1858 if (read_size < size)
1860 buffer[read_size] = 0;
1865 buffer = g_realloc (buffer, size);
1868 g_set_error_literal (error,
1871 _("Symbolic links not supported"));
1877 /* NOTE : Keep this part last to ensure nothing in this file uses the
1878 * below binary compatibility versions.
1880 #if defined (G_OS_WIN32) && !defined (_WIN64)
1882 /* Binary compatibility versions. Will be called by code compiled
1883 * against quite old (pre-2.8, I think) headers only, not from more
1884 * recently compiled code.
1890 g_file_test (const gchar *filename,
1893 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
1896 if (utf8_filename == NULL)
1899 retval = g_file_test_utf8 (utf8_filename, test);
1901 g_free (utf8_filename);
1906 #undef g_file_get_contents
1909 g_file_get_contents (const gchar *filename,
1914 gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
1917 if (utf8_filename == NULL)
1920 retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
1922 g_free (utf8_filename);
1930 g_mkstemp (gchar *tmpl)
1934 static const char letters[] =
1935 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1936 static const int NLETTERS = sizeof (letters) - 1;
1939 static int counter = 0;
1941 /* find the last occurrence of 'XXXXXX' */
1942 XXXXXX = g_strrstr (tmpl, "XXXXXX");
1950 /* Get some more or less random data. */
1951 g_get_current_time (&tv);
1952 value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1954 for (count = 0; count < 100; value += 7777, ++count)
1958 /* Fill in the random bits. */
1959 XXXXXX[0] = letters[v % NLETTERS];
1961 XXXXXX[1] = letters[v % NLETTERS];
1963 XXXXXX[2] = letters[v % NLETTERS];
1965 XXXXXX[3] = letters[v % NLETTERS];
1967 XXXXXX[4] = letters[v % NLETTERS];
1969 XXXXXX[5] = letters[v % NLETTERS];
1971 /* This is the backward compatibility system codepage version,
1972 * thus use normal open().
1974 fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
1978 else if (errno != EEXIST)
1979 /* Any other error will apply also to other names we might
1980 * try, and there are 2^32 or so of them, so give up now.
1985 /* We got out of the loop because we ran out of combinations to try. */
1990 #undef g_file_open_tmp
1993 g_file_open_tmp (const gchar *tmpl,
1997 gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
1998 gchar *utf8_name_used;
2001 if (utf8_tmpl == NULL)
2004 retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
2010 *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
2012 g_free (utf8_name_used);
2019 #define __G_FILEUTILS_C__
2020 #include "galiasdef.c"