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 * <informalexample><programlisting>
159 * /* DON'T DO THIS */
160 * if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) {
161 * fd = g_open (filename, O_WRONLY);
162 * /* write to fd */
164 * </programlisting></informalexample>
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
195 if (G_WIN32_HAVE_WIDECHAR_API ())
197 wchar_t *wfilename
= g_utf8_to_utf16 (filename
, -1, NULL
, NULL
, NULL
);
199 if (wfilename
== NULL
)
202 attributes
= GetFileAttributesW (wfilename
);
208 gchar
*cpfilename
= g_locale_from_utf8 (filename
, -1, NULL
, NULL
, NULL
);
210 if (cpfilename
== NULL
)
213 attributes
= GetFileAttributesA (cpfilename
);
218 if (attributes
== INVALID_FILE_ATTRIBUTES
)
221 if (test
& G_FILE_TEST_EXISTS
)
224 if (test
& G_FILE_TEST_IS_REGULAR
)
225 return (attributes
& (FILE_ATTRIBUTE_DIRECTORY
| FILE_ATTRIBUTE_DEVICE
)) == 0;
227 if (test
& G_FILE_TEST_IS_DIR
)
228 return (attributes
& FILE_ATTRIBUTE_DIRECTORY
) != 0;
230 if (test
& G_FILE_TEST_IS_EXECUTABLE
)
232 const gchar
*lastdot
= strrchr (filename
, '.');
233 const gchar
*pathext
= NULL
, *p
;
239 if (stricmp (lastdot
, ".exe") == 0 ||
240 stricmp (lastdot
, ".cmd") == 0 ||
241 stricmp (lastdot
, ".bat") == 0 ||
242 stricmp (lastdot
, ".com") == 0)
245 /* Check if it is one of the types listed in %PATHEXT% */
247 pathext
= g_getenv ("PATHEXT");
251 pathext
= g_utf8_casefold (pathext
, -1);
253 lastdot
= g_utf8_casefold (lastdot
, -1);
254 extlen
= strlen (lastdot
);
259 const gchar
*q
= strchr (p
, ';');
262 if (extlen
== q
- p
&&
263 memcmp (lastdot
, p
, extlen
) == 0)
265 g_free ((gchar
*) pathext
);
266 g_free ((gchar
*) lastdot
);
275 g_free ((gchar
*) pathext
);
276 g_free ((gchar
*) lastdot
);
282 if ((test
& G_FILE_TEST_EXISTS
) && (access (filename
, F_OK
) == 0))
285 if ((test
& G_FILE_TEST_IS_EXECUTABLE
) && (access (filename
, X_OK
) == 0))
290 /* For root, on some POSIX systems, access (filename, X_OK)
291 * will succeed even if no executable bits are set on the
292 * file. We fall through to a stat test to avoid that.
296 test
&= ~G_FILE_TEST_IS_EXECUTABLE
;
298 if (test
& G_FILE_TEST_IS_SYMLINK
)
302 if ((lstat (filename
, &s
) == 0) && S_ISLNK (s
.st_mode
))
306 if (test
& (G_FILE_TEST_IS_REGULAR
|
308 G_FILE_TEST_IS_EXECUTABLE
))
312 if (stat (filename
, &s
) == 0)
314 if ((test
& G_FILE_TEST_IS_REGULAR
) && S_ISREG (s
.st_mode
))
317 if ((test
& G_FILE_TEST_IS_DIR
) && S_ISDIR (s
.st_mode
))
320 /* The extra test for root when access (file, X_OK) succeeds.
322 if ((test
& G_FILE_TEST_IS_EXECUTABLE
) &&
323 ((s
.st_mode
& S_IXOTH
) ||
324 (s
.st_mode
& S_IXUSR
) ||
325 (s
.st_mode
& S_IXGRP
)))
338 /* Binary compatibility version. Not for newly compiled code. */
341 g_file_test (const gchar
*filename
,
344 gchar
*utf8_filename
= g_locale_to_utf8 (filename
, -1, NULL
, NULL
, NULL
);
347 if (utf8_filename
== NULL
)
350 retval
= g_file_test_utf8 (utf8_filename
, test
);
352 g_free (utf8_filename
);
360 g_file_error_quark (void)
362 return g_quark_from_static_string ("g-file-error-quark");
366 * g_file_error_from_errno:
367 * @err_no: an "errno" value
369 * Gets a #GFileError constant based on the passed-in @errno.
370 * For example, if you pass in %EEXIST this function returns
371 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
372 * assume that all #GFileError values will exist.
374 * Normally a #GFileError value goes into a #GError returned
375 * from a function that manipulates files. So you would use
376 * g_file_error_from_errno() when constructing a #GError.
378 * Return value: #GFileError corresponding to the given @errno
381 g_file_error_from_errno (gint err_no
)
387 return G_FILE_ERROR_EXIST
;
393 return G_FILE_ERROR_ISDIR
;
399 return G_FILE_ERROR_ACCES
;
405 return G_FILE_ERROR_NAMETOOLONG
;
411 return G_FILE_ERROR_NOENT
;
417 return G_FILE_ERROR_NOTDIR
;
423 return G_FILE_ERROR_NXIO
;
429 return G_FILE_ERROR_NODEV
;
435 return G_FILE_ERROR_ROFS
;
441 return G_FILE_ERROR_TXTBSY
;
447 return G_FILE_ERROR_FAULT
;
453 return G_FILE_ERROR_LOOP
;
459 return G_FILE_ERROR_NOSPC
;
465 return G_FILE_ERROR_NOMEM
;
471 return G_FILE_ERROR_MFILE
;
477 return G_FILE_ERROR_NFILE
;
483 return G_FILE_ERROR_BADF
;
489 return G_FILE_ERROR_INVAL
;
495 return G_FILE_ERROR_PIPE
;
501 return G_FILE_ERROR_AGAIN
;
507 return G_FILE_ERROR_INTR
;
513 return G_FILE_ERROR_IO
;
519 return G_FILE_ERROR_PERM
;
525 return G_FILE_ERROR_NOSYS
;
530 return G_FILE_ERROR_FAILED
;
536 get_contents_stdio (const gchar
*display_filename
,
545 size_t total_bytes
= 0;
546 size_t total_allocated
= 0;
549 g_assert (f
!= NULL
);
555 bytes
= fread (buf
, 1, sizeof (buf
), f
);
558 while ((total_bytes
+ bytes
+ 1) > total_allocated
)
561 total_allocated
*= 2;
563 total_allocated
= MIN (bytes
+ 1, sizeof (buf
));
565 tmp
= g_try_realloc (str
, total_allocated
);
572 _("Could not allocate %lu bytes to read file \"%s\""),
573 (gulong
) total_allocated
,
586 g_file_error_from_errno (save_errno
),
587 _("Error reading file '%s': %s"),
589 g_strerror (save_errno
));
594 memcpy (str
+ total_bytes
, buf
, bytes
);
595 total_bytes
+= bytes
;
600 if (total_allocated
== 0)
601 str
= g_new (gchar
, 1);
603 str
[total_bytes
] = '\0';
606 *length
= total_bytes
;
623 get_contents_regfile (const gchar
*display_filename
,
624 struct stat
*stat_buf
,
635 size
= stat_buf
->st_size
;
637 alloc_size
= size
+ 1;
638 buf
= g_try_malloc (alloc_size
);
645 _("Could not allocate %lu bytes to read file \"%s\""),
653 while (bytes_read
< size
)
657 rc
= read (fd
, buf
+ bytes_read
, size
- bytes_read
);
663 int save_errno
= errno
;
668 g_file_error_from_errno (save_errno
),
669 _("Failed to read from file '%s': %s"),
671 g_strerror (save_errno
));
682 buf
[bytes_read
] = '\0';
685 *length
= bytes_read
;
701 get_contents_posix (const gchar
*filename
,
706 struct stat stat_buf
;
708 gchar
*display_filename
= g_filename_display_name (filename
);
710 /* O_BINARY useful on Cygwin */
711 fd
= open (filename
, O_RDONLY
|O_BINARY
);
715 int save_errno
= errno
;
719 g_file_error_from_errno (save_errno
),
720 _("Failed to open file '%s': %s"),
722 g_strerror (save_errno
));
723 g_free (display_filename
);
728 /* I don't think this will ever fail, aside from ENOMEM, but. */
729 if (fstat (fd
, &stat_buf
) < 0)
731 int save_errno
= errno
;
736 g_file_error_from_errno (save_errno
),
737 _("Failed to get attributes of file '%s': fstat() failed: %s"),
739 g_strerror (save_errno
));
740 g_free (display_filename
);
745 if (stat_buf
.st_size
> 0 && S_ISREG (stat_buf
.st_mode
))
747 gboolean retval
= get_contents_regfile (display_filename
,
753 g_free (display_filename
);
762 f
= fdopen (fd
, "r");
766 int save_errno
= errno
;
770 g_file_error_from_errno (save_errno
),
771 _("Failed to open file '%s': fdopen() failed: %s"),
773 g_strerror (save_errno
));
774 g_free (display_filename
);
779 retval
= get_contents_stdio (display_filename
, f
, contents
, length
, error
);
780 g_free (display_filename
);
786 #else /* G_OS_WIN32 */
789 get_contents_win32 (const gchar
*filename
,
796 gchar
*display_filename
= g_filename_display_name (filename
);
799 f
= g_fopen (filename
, "rb");
806 g_file_error_from_errno (save_errno
),
807 _("Failed to open file '%s': %s"),
809 g_strerror (save_errno
));
810 g_free (display_filename
);
815 retval
= get_contents_stdio (display_filename
, f
, contents
, length
, error
);
816 g_free (display_filename
);
824 * g_file_get_contents:
825 * @filename: name of a file to read contents from, in the GLib file name encoding
826 * @contents: location to store an allocated string
827 * @length: location to store length in bytes of the contents, or %NULL
828 * @error: return location for a #GError, or %NULL
830 * Reads an entire file into allocated memory, with good error
833 * If the call was successful, it returns %TRUE and sets @contents to the file
834 * contents and @length to the length of the file contents in bytes. The string
835 * stored in @contents will be nul-terminated, so for text files you can pass
836 * %NULL for the @length argument. If the call was not successful, it returns
837 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
838 * codes are those in the #GFileError enumeration. In the error case,
839 * @contents is set to %NULL and @length is set to zero.
841 * Return value: %TRUE on success, %FALSE if an error occurred
844 g_file_get_contents (const gchar
*filename
,
849 g_return_val_if_fail (filename
!= NULL
, FALSE
);
850 g_return_val_if_fail (contents
!= NULL
, FALSE
);
857 return get_contents_win32 (filename
, contents
, length
, error
);
859 return get_contents_posix (filename
, contents
, length
, error
);
865 #undef g_file_get_contents
867 /* Binary compatibility version. Not for newly compiled code. */
870 g_file_get_contents (const gchar
*filename
,
875 gchar
*utf8_filename
= g_locale_to_utf8 (filename
, -1, NULL
, NULL
, error
);
878 if (utf8_filename
== NULL
)
881 retval
= g_file_get_contents_utf8 (utf8_filename
, contents
, length
, error
);
883 g_free (utf8_filename
);
891 rename_file (const char *old_name
,
892 const char *new_name
,
896 if (g_rename (old_name
, new_name
) == -1)
898 int save_errno
= errno
;
899 gchar
*display_old_name
= g_filename_display_name (old_name
);
900 gchar
*display_new_name
= g_filename_display_name (new_name
);
904 g_file_error_from_errno (save_errno
),
905 _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
908 g_strerror (save_errno
));
910 g_free (display_old_name
);
911 g_free (display_new_name
);
920 write_to_temp_file (const gchar
*contents
,
922 const gchar
*template,
934 tmp_name
= g_strdup_printf ("%s.XXXXXX", template);
937 fd
= create_temp_file (tmp_name
, 0666);
938 display_name
= g_filename_display_name (tmp_name
);
945 g_file_error_from_errno (save_errno
),
946 _("Failed to create file '%s': %s"),
947 display_name
, g_strerror (save_errno
));
953 file
= fdopen (fd
, "wb");
959 g_file_error_from_errno (save_errno
),
960 _("Failed to open file '%s' for writing: fdopen() failed: %s"),
962 g_strerror (save_errno
));
976 n_written
= fwrite (contents
, 1, length
, file
);
978 if (n_written
< length
)
984 g_file_error_from_errno (save_errno
),
985 _("Failed to write file '%s': fwrite() failed: %s"),
987 g_strerror (save_errno
));
997 if (fclose (file
) == EOF
)
1003 g_file_error_from_errno (save_errno
),
1004 _("Failed to close file '%s': fclose() failed: %s"),
1006 g_strerror (save_errno
));
1008 g_unlink (tmp_name
);
1013 retval
= g_strdup (tmp_name
);
1017 g_free (display_name
);
1023 * g_file_set_contents:
1024 * @filename: name of a file to write @contents to, in the GLib file name
1026 * @contents: string to write to the file
1027 * @length: length of @contents, or -1 if @contents is a nul-terminated string
1028 * @error: return location for a #GError, or %NULL
1030 * Writes all of @contents to a file named @filename, with good error checking.
1031 * If a file called @filename already exists it will be overwritten.
1033 * This write is atomic in the sense that it is first written to a temporary
1034 * file which is then renamed to the final name. Notes:
1037 * On Unix, if @filename already exists hard links to @filename will break.
1038 * Also since the file is recreated, existing permissions, access control
1039 * lists, metadata etc. may be lost. If @filename is a symbolic link,
1040 * the link itself will be replaced, not the linked file.
1043 * On Windows renaming a file will not remove an existing file with the
1044 * new name, so on Windows there is a race condition between the existing
1045 * file being removed and the temporary file being renamed.
1048 * On Windows there is no way to remove a file that is open to some
1049 * process, or mapped into memory. Thus, this function will fail if
1050 * @filename already exists and is open.
1054 * If the call was sucessful, it returns %TRUE. If the call was not successful,
1055 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1056 * Possible error codes are those in the #GFileError enumeration.
1058 * Return value: %TRUE on success, %FALSE if an error occurred
1063 g_file_set_contents (const gchar
*filename
,
1064 const gchar
*contents
,
1068 gchar
*tmp_filename
;
1070 GError
*rename_error
= NULL
;
1072 g_return_val_if_fail (filename
!= NULL
, FALSE
);
1073 g_return_val_if_fail (error
== NULL
|| *error
== NULL
, FALSE
);
1074 g_return_val_if_fail (contents
!= NULL
|| length
== 0, FALSE
);
1075 g_return_val_if_fail (length
>= -1, FALSE
);
1078 length
= strlen (contents
);
1080 tmp_filename
= write_to_temp_file (contents
, length
, filename
, error
);
1088 if (!rename_file (tmp_filename
, filename
, &rename_error
))
1092 g_unlink (tmp_filename
);
1093 g_propagate_error (error
, rename_error
);
1097 #else /* G_OS_WIN32 */
1099 /* Renaming failed, but on Windows this may just mean
1100 * the file already exists. So if the target file
1101 * exists, try deleting it and do the rename again.
1103 if (!g_file_test (filename
, G_FILE_TEST_EXISTS
))
1105 g_unlink (tmp_filename
);
1106 g_propagate_error (error
, rename_error
);
1111 g_error_free (rename_error
);
1113 if (g_unlink (filename
) == -1)
1115 gchar
*display_filename
= g_filename_display_name (filename
);
1117 int save_errno
= errno
;
1121 g_file_error_from_errno (save_errno
),
1122 _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1124 g_strerror (save_errno
));
1126 g_free (display_filename
);
1127 g_unlink (tmp_filename
);
1132 if (!rename_file (tmp_filename
, filename
, error
))
1134 g_unlink (tmp_filename
);
1145 g_free (tmp_filename
);
1150 * create_temp_file based on the mkstemp implementation from the GNU C library.
1151 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1154 create_temp_file (gchar
*tmpl
,
1159 static const char letters
[] =
1160 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1161 static const int NLETTERS
= sizeof (letters
) - 1;
1164 static int counter
= 0;
1166 /* find the last occurrence of "XXXXXX" */
1167 XXXXXX
= g_strrstr (tmpl
, "XXXXXX");
1169 if (!XXXXXX
|| strncmp (XXXXXX
, "XXXXXX", 6))
1175 /* Get some more or less random data. */
1176 g_get_current_time (&tv
);
1177 value
= (tv
.tv_usec
^ tv
.tv_sec
) + counter
++;
1179 for (count
= 0; count
< 100; value
+= 7777, ++count
)
1183 /* Fill in the random bits. */
1184 XXXXXX
[0] = letters
[v
% NLETTERS
];
1186 XXXXXX
[1] = letters
[v
% NLETTERS
];
1188 XXXXXX
[2] = letters
[v
% NLETTERS
];
1190 XXXXXX
[3] = letters
[v
% NLETTERS
];
1192 XXXXXX
[4] = letters
[v
% NLETTERS
];
1194 XXXXXX
[5] = letters
[v
% NLETTERS
];
1196 /* tmpl is in UTF-8 on Windows, thus use g_open() */
1197 fd
= g_open (tmpl
, O_RDWR
| O_CREAT
| O_EXCL
| O_BINARY
, permissions
);
1201 else if (errno
!= EEXIST
)
1202 /* Any other error will apply also to other names we might
1203 * try, and there are 2^32 or so of them, so give up now.
1208 /* We got out of the loop because we ran out of combinations to try. */
1215 * @tmpl: template filename
1217 * Opens a temporary file. See the mkstemp() documentation
1218 * on most UNIX-like systems.
1220 * The parameter is a string that should follow the rules for
1221 * mkstemp() templates, i.e. contain the string "XXXXXX".
1222 * g_mkstemp() is slightly more flexible than mkstemp()
1223 * in that the sequence does not have to occur at the very end of the
1224 * template. The X string will
1225 * be modified to form the name of a file that didn't exist.
1226 * The string should be in the GLib file name encoding. Most importantly,
1227 * on Windows it should be in UTF-8.
1229 * Return value: A file handle (as from open()) to the file
1230 * opened for reading and writing. The file is opened in binary mode
1231 * on platforms where there is a difference. The file handle should be
1232 * closed with close(). In case of errors, -1 is returned.
1235 g_mkstemp (gchar
*tmpl
)
1237 return create_temp_file (tmpl
, 0600);
1244 /* Binary compatibility version. Not for newly compiled code. */
1247 g_mkstemp (gchar
*tmpl
)
1251 static const char letters
[] =
1252 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1253 static const int NLETTERS
= sizeof (letters
) - 1;
1256 static int counter
= 0;
1258 /* find the last occurrence of 'XXXXXX' */
1259 XXXXXX
= g_strrstr (tmpl
, "XXXXXX");
1261 if (!XXXXXX
|| strcmp (XXXXXX
, "XXXXXX"))
1267 /* Get some more or less random data. */
1268 g_get_current_time (&tv
);
1269 value
= (tv
.tv_usec
^ tv
.tv_sec
) + counter
++;
1271 for (count
= 0; count
< 100; value
+= 7777, ++count
)
1275 /* Fill in the random bits. */
1276 XXXXXX
[0] = letters
[v
% NLETTERS
];
1278 XXXXXX
[1] = letters
[v
% NLETTERS
];
1280 XXXXXX
[2] = letters
[v
% NLETTERS
];
1282 XXXXXX
[3] = letters
[v
% NLETTERS
];
1284 XXXXXX
[4] = letters
[v
% NLETTERS
];
1286 XXXXXX
[5] = letters
[v
% NLETTERS
];
1288 /* This is the backward compatibility system codepage version,
1289 * thus use normal open().
1291 fd
= open (tmpl
, O_RDWR
| O_CREAT
| O_EXCL
| O_BINARY
, 0600);
1295 else if (errno
!= EEXIST
)
1296 /* Any other error will apply also to other names we might
1297 * try, and there are 2^32 or so of them, so give up now.
1302 /* We got out of the loop because we ran out of combinations to try. */
1311 * @tmpl: Template for file name, as in g_mkstemp(), basename only,
1312 * or %NULL, to a default template
1313 * @name_used: location to store actual name used
1314 * @error: return location for a #GError
1316 * Opens a file for writing in the preferred directory for temporary
1317 * files (as returned by g_get_tmp_dir()).
1319 * @tmpl should be a string in the GLib file name encoding containing
1320 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1321 * However, unlike these functions, the template should only be a
1322 * basename, no directory components are allowed. If template is
1323 * %NULL, a default template is used.
1325 * Note that in contrast to g_mkstemp() (and mkstemp())
1326 * @tmpl is not modified, and might thus be a read-only literal string.
1328 * The actual name used is returned in @name_used if non-%NULL. This
1329 * string should be freed with g_free() when not needed any longer.
1330 * The returned name is in the GLib file name encoding.
1332 * Return value: A file handle (as from open()) to
1333 * the file opened for reading and writing. The file is opened in binary
1334 * mode on platforms where there is a difference. The file handle should be
1335 * closed with close(). In case of errors, -1 is returned
1336 * and @error will be set.
1339 g_file_open_tmp (const gchar
*tmpl
,
1352 if ((slash
= strchr (tmpl
, G_DIR_SEPARATOR
)) != NULL
1354 || (strchr (tmpl
, '/') != NULL
&& (slash
= "/"))
1358 gchar
*display_tmpl
= g_filename_display_name (tmpl
);
1365 G_FILE_ERROR_FAILED
,
1366 _("Template '%s' invalid, should not contain a '%s'"),
1368 g_free (display_tmpl
);
1373 if (strstr (tmpl
, "XXXXXX") == NULL
)
1375 gchar
*display_tmpl
= g_filename_display_name (tmpl
);
1378 G_FILE_ERROR_FAILED
,
1379 _("Template '%s' doesn't contain XXXXXX"),
1381 g_free (display_tmpl
);
1385 tmpdir
= g_get_tmp_dir ();
1387 if (G_IS_DIR_SEPARATOR (tmpdir
[strlen (tmpdir
) - 1]))
1390 sep
= G_DIR_SEPARATOR_S
;
1392 fulltemplate
= g_strconcat (tmpdir
, sep
, tmpl
, NULL
);
1394 retval
= g_mkstemp (fulltemplate
);
1398 int save_errno
= errno
;
1399 gchar
*display_fulltemplate
= g_filename_display_name (fulltemplate
);
1403 g_file_error_from_errno (save_errno
),
1404 _("Failed to create file '%s': %s"),
1405 display_fulltemplate
, g_strerror (save_errno
));
1406 g_free (display_fulltemplate
);
1407 g_free (fulltemplate
);
1412 *name_used
= fulltemplate
;
1414 g_free (fulltemplate
);
1421 #undef g_file_open_tmp
1423 /* Binary compatibility version. Not for newly compiled code. */
1426 g_file_open_tmp (const gchar
*tmpl
,
1430 gchar
*utf8_tmpl
= g_locale_to_utf8 (tmpl
, -1, NULL
, NULL
, error
);
1431 gchar
*utf8_name_used
;
1434 if (utf8_tmpl
== NULL
)
1437 retval
= g_file_open_tmp_utf8 (utf8_tmpl
, &utf8_name_used
, error
);
1443 *name_used
= g_locale_from_utf8 (utf8_name_used
, -1, NULL
, NULL
, NULL
);
1445 g_free (utf8_name_used
);
1453 g_build_path_va (const gchar
*separator
,
1454 const gchar
*first_element
,
1459 gint separator_len
= strlen (separator
);
1460 gboolean is_first
= TRUE
;
1461 gboolean have_leading
= FALSE
;
1462 const gchar
*single_element
= NULL
;
1463 const gchar
*next_element
;
1464 const gchar
*last_trailing
= NULL
;
1467 result
= g_string_new (NULL
);
1470 next_element
= str_array
[i
++];
1472 next_element
= first_element
;
1476 const gchar
*element
;
1482 element
= next_element
;
1484 next_element
= str_array
[i
++];
1486 next_element
= va_arg (*args
, gchar
*);
1491 /* Ignore empty elements */
1500 strncmp (start
, separator
, separator_len
) == 0)
1501 start
+= separator_len
;
1504 end
= start
+ strlen (start
);
1508 while (end
>= start
+ separator_len
&&
1509 strncmp (end
- separator_len
, separator
, separator_len
) == 0)
1510 end
-= separator_len
;
1512 last_trailing
= end
;
1513 while (last_trailing
>= element
+ separator_len
&&
1514 strncmp (last_trailing
- separator_len
, separator
, separator_len
) == 0)
1515 last_trailing
-= separator_len
;
1519 /* If the leading and trailing separator strings are in the
1520 * same element and overlap, the result is exactly that element
1522 if (last_trailing
<= start
)
1523 single_element
= element
;
1525 g_string_append_len (result
, element
, start
- element
);
1526 have_leading
= TRUE
;
1529 single_element
= NULL
;
1536 g_string_append (result
, separator
);
1538 g_string_append_len (result
, start
, end
- start
);
1544 g_string_free (result
, TRUE
);
1545 return g_strdup (single_element
);
1550 g_string_append (result
, last_trailing
);
1552 return g_string_free (result
, FALSE
);
1558 * @separator: a string used to separator the elements of the path.
1559 * @args: %NULL-terminated array of strings containing the path elements.
1561 * Behaves exactly like g_build_path(), but takes the path elements
1562 * as a string array, instead of varargs. This function is mainly
1563 * meant for language bindings.
1565 * Return value: a newly-allocated string that must be freed with g_free().
1570 g_build_pathv (const gchar
*separator
,
1576 return g_build_path_va (separator
, NULL
, NULL
, args
);
1582 * @separator: a string used to separator the elements of the path.
1583 * @first_element: the first element in the path
1584 * @Varargs: remaining elements in path, terminated by %NULL
1586 * Creates a path from a series of elements using @separator as the
1587 * separator between elements. At the boundary between two elements,
1588 * any trailing occurrences of separator in the first element, or
1589 * leading occurrences of separator in the second element are removed
1590 * and exactly one copy of the separator is inserted.
1592 * Empty elements are ignored.
1594 * The number of leading copies of the separator on the result is
1595 * the same as the number of leading copies of the separator on
1596 * the first non-empty element.
1598 * The number of trailing copies of the separator on the result is
1599 * the same as the number of trailing copies of the separator on
1600 * the last non-empty element. (Determination of the number of
1601 * trailing copies is done without stripping leading copies, so
1602 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1603 * has 1 trailing copy.)
1605 * However, if there is only a single non-empty element, and there
1606 * are no characters in that element not part of the leading or
1607 * trailing separators, then the result is exactly the original value
1610 * Other than for determination of the number of leading and trailing
1611 * copies of the separator, elements consisting only of copies
1612 * of the separator are ignored.
1614 * Return value: a newly-allocated string that must be freed with g_free().
1617 g_build_path (const gchar
*separator
,
1618 const gchar
*first_element
,
1624 g_return_val_if_fail (separator
!= NULL
, NULL
);
1626 va_start (args
, first_element
);
1627 str
= g_build_path_va (separator
, first_element
, &args
, NULL
);
1636 g_build_pathname_va (const gchar
*first_element
,
1640 /* Code copied from g_build_pathv(), and modified to use two
1641 * alternative single-character separators.
1644 gboolean is_first
= TRUE
;
1645 gboolean have_leading
= FALSE
;
1646 const gchar
*single_element
= NULL
;
1647 const gchar
*next_element
;
1648 const gchar
*last_trailing
= NULL
;
1649 gchar current_separator
= '\\';
1652 result
= g_string_new (NULL
);
1655 next_element
= str_array
[i
++];
1657 next_element
= first_element
;
1661 const gchar
*element
;
1667 element
= next_element
;
1669 next_element
= str_array
[i
++];
1671 next_element
= va_arg (*args
, gchar
*);
1676 /* Ignore empty elements */
1685 (*start
== '\\' || *start
== '/'))
1687 current_separator
= *start
;
1692 end
= start
+ strlen (start
);
1696 while (end
>= start
+ 1 &&
1697 (end
[-1] == '\\' || end
[-1] == '/'))
1699 current_separator
= end
[-1];
1703 last_trailing
= end
;
1704 while (last_trailing
>= element
+ 1 &&
1705 (last_trailing
[-1] == '\\' || last_trailing
[-1] == '/'))
1710 /* If the leading and trailing separator strings are in the
1711 * same element and overlap, the result is exactly that element
1713 if (last_trailing
<= start
)
1714 single_element
= element
;
1716 g_string_append_len (result
, element
, start
- element
);
1717 have_leading
= TRUE
;
1720 single_element
= NULL
;
1727 g_string_append_len (result
, ¤t_separator
, 1);
1729 g_string_append_len (result
, start
, end
- start
);
1735 g_string_free (result
, TRUE
);
1736 return g_strdup (single_element
);
1741 g_string_append (result
, last_trailing
);
1743 return g_string_free (result
, FALSE
);
1750 * g_build_filenamev:
1751 * @args: %NULL-terminated array of strings containing the path elements.
1753 * Behaves exactly like g_build_filename(), but takes the path elements
1754 * as a string array, instead of varargs. This function is mainly
1755 * meant for language bindings.
1757 * Return value: a newly-allocated string that must be freed with g_free().
1762 g_build_filenamev (gchar
**args
)
1767 str
= g_build_path_va (G_DIR_SEPARATOR_S
, NULL
, NULL
, args
);
1769 str
= g_build_pathname_va (NULL
, NULL
, args
);
1777 * @first_element: the first element in the path
1778 * @Varargs: remaining elements in path, terminated by %NULL
1780 * Creates a filename from a series of elements using the correct
1781 * separator for filenames.
1783 * On Unix, this function behaves identically to <literal>g_build_path
1784 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1786 * On Windows, it takes into account that either the backslash
1787 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1788 * as separator in filenames, but otherwise behaves as on Unix. When
1789 * file pathname separators need to be inserted, the one that last
1790 * previously occurred in the parameters (reading from left to right)
1793 * No attempt is made to force the resulting filename to be an absolute
1794 * path. If the first element is a relative path, the result will
1795 * be a relative path.
1797 * Return value: a newly-allocated string that must be freed with g_free().
1800 g_build_filename (const gchar
*first_element
,
1806 va_start (args
, first_element
);
1808 str
= g_build_path_va (G_DIR_SEPARATOR_S
, first_element
, &args
, NULL
);
1810 str
= g_build_pathname_va (first_element
, &args
, NULL
);
1819 * @filename: the symbolic link
1820 * @error: return location for a #GError
1822 * Reads the contents of the symbolic link @filename like the POSIX
1823 * readlink() function. The returned string is in the encoding used
1824 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
1826 * Returns: A newly allocated string with the contents of the symbolic link,
1827 * or %NULL if an error occurred.
1832 g_file_read_link (const gchar
*filename
,
1835 #ifdef HAVE_READLINK
1841 buffer
= g_malloc (size
);
1845 read_size
= readlink (filename
, buffer
, size
);
1846 if (read_size
< 0) {
1847 int save_errno
= errno
;
1848 gchar
*display_filename
= g_filename_display_name (filename
);
1853 g_file_error_from_errno (save_errno
),
1854 _("Failed to read the symbolic link '%s': %s"),
1856 g_strerror (save_errno
));
1857 g_free (display_filename
);
1862 if (read_size
< size
)
1864 buffer
[read_size
] = 0;
1869 buffer
= g_realloc (buffer
, size
);
1875 _("Symbolic links not supported"));
1881 #define __G_FILEUTILS_C__
1882 #include "galiasdef.c"