88a647d59b10ec68894fc7c3fef6f922ce6005c9
[platform/upstream/glib.git] / glib / gfileutils.c
1 /* gfileutils.c - File utility functions
2  *
3  *  Copyright 2000 Red Hat, Inc.
4  *
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.
9  *
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.
14  *
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.
19  */
20
21 #include "config.h"
22 #include "glibconfig.h"
23
24 #include <sys/stat.h>
25 #ifdef HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <string.h>
32 #include <errno.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <fcntl.h>
36 #include <stdlib.h>
37
38 #ifdef G_OS_WIN32
39 #include <windows.h>
40 #include <io.h>
41 #endif /* G_OS_WIN32 */
42
43 #ifndef S_ISLNK
44 #define S_ISLNK(x) 0
45 #endif
46
47 #ifndef O_BINARY
48 #define O_BINARY 0
49 #endif
50
51 #include "gfileutils.h"
52
53 #include "gstdio.h"
54 #include "glibintl.h"
55
56 #ifdef HAVE_LINUX_MAGIC_H /* for btrfs check */
57 #include <linux/magic.h>
58 #include <sys/vfs.h>
59 #endif
60
61
62 /**
63  * SECTION:fileutils
64  * @title: File Utilities
65  * @short_description: various file-related functions
66  *
67  * There is a group of functions which wrap the common POSIX functions
68  * dealing with filenames (g_open(), g_rename(), g_mkdir(), g_stat(),
69  * g_unlink(), g_remove(), g_fopen(), g_freopen()). The point of these
70  * wrappers is to make it possible to handle file names with any Unicode
71  * characters in them on Windows without having to use ifdefs and the
72  * wide character API in the application code.
73  *
74  * The pathname argument should be in the GLib file name encoding.
75  * On POSIX this is the actual on-disk encoding which might correspond
76  * to the locale settings of the process (or the
77  * <envar>G_FILENAME_ENCODING</envar> environment variable), or not.
78  *
79  * On Windows the GLib file name encoding is UTF-8. Note that the
80  * Microsoft C library does not use UTF-8, but has separate APIs for
81  * current system code page and wide characters (UTF-16). The GLib
82  * wrappers call the wide character API if present (on modern Windows
83  * systems), otherwise convert to/from the system code page.
84  *
85  * Another group of functions allows to open and read directories
86  * in the GLib file name encoding. These are g_dir_open(),
87  * g_dir_read_name(), g_dir_rewind(), g_dir_close().
88  */
89
90 /**
91  * GFileError:
92  * @G_FILE_ERROR_EXIST: Operation not permitted; only the owner of
93  *     the file (or other resource) or processes with special privileges
94  *     can perform the operation.
95  * @G_FILE_ERROR_ISDIR: File is a directory; you cannot open a directory
96  *     for writing, or create or remove hard links to it.
97  * @G_FILE_ERROR_ACCES: Permission denied; the file permissions do not
98  *     allow the attempted operation.
99  * @G_FILE_ERROR_NAMETOOLONG: Filename too long.
100  * @G_FILE_ERROR_NOENT: No such file or directory. This is a "file
101  *     doesn't exist" error for ordinary files that are referenced in
102  *     contexts where they are expected to already exist.
103  * @G_FILE_ERROR_NOTDIR: A file that isn't a directory was specified when
104  *     a directory is required.
105  * @G_FILE_ERROR_NXIO: No such device or address. The system tried to
106  *     use the device represented by a file you specified, and it
107  *     couldn't find the device. This can mean that the device file was
108  *     installed incorrectly, or that the physical device is missing or
109  *     not correctly attached to the computer.
110  * @G_FILE_ERROR_NODEV: The underlying file system of the specified file
111  *     does not support memory mapping.
112  * @G_FILE_ERROR_ROFS: The directory containing the new link can't be
113  *     modified because it's on a read-only file system.
114  * @G_FILE_ERROR_TXTBSY: Text file busy.
115  * @G_FILE_ERROR_FAULT: You passed in a pointer to bad memory.
116  *     (GLib won't reliably return this, don't pass in pointers to bad
117  *     memory.)
118  * @G_FILE_ERROR_LOOP: Too many levels of symbolic links were encountered
119  *     in looking up a file name. This often indicates a cycle of symbolic
120  *     links.
121  * @G_FILE_ERROR_NOSPC: No space left on device; write operation on a
122  *     file failed because the disk is full.
123  * @G_FILE_ERROR_NOMEM: No memory available. The system cannot allocate
124  *     more virtual memory because its capacity is full.
125  * @G_FILE_ERROR_MFILE: The current process has too many files open and
126  *     can't open any more. Duplicate descriptors do count toward this
127  *     limit.
128  * @G_FILE_ERROR_NFILE: There are too many distinct file openings in the
129  *     entire system.
130  * @G_FILE_ERROR_BADF: Bad file descriptor; for example, I/O on a
131  *     descriptor that has been closed or reading from a descriptor open
132  *     only for writing (or vice versa).
133  * @G_FILE_ERROR_INVAL: Invalid argument. This is used to indicate
134  *     various kinds of problems with passing the wrong argument to a
135  *     library function.
136  * @G_FILE_ERROR_PIPE: Broken pipe; there is no process reading from the
137  *     other end of a pipe. Every library function that returns this
138  *     error code also generates a 'SIGPIPE' signal; this signal
139  *     terminates the program if not handled or blocked. Thus, your
140  *     program will never actually see this code unless it has handled
141  *     or blocked 'SIGPIPE'.
142  * @G_FILE_ERROR_AGAIN: Resource temporarily unavailable; the call might
143  *     work if you try again later.
144  * @G_FILE_ERROR_INTR: Interrupted function call; an asynchronous signal
145  *     occurred and prevented completion of the call. When this
146  *     happens, you should try the call again.
147  * @G_FILE_ERROR_IO: Input/output error; usually used for physical read
148  *    or write errors. i.e. the disk or other physical device hardware
149  *    is returning errors.
150  * @G_FILE_ERROR_PERM: Operation not permitted; only the owner of the
151  *    file (or other resource) or processes with special privileges can
152  *    perform the operation.
153  * @G_FILE_ERROR_NOSYS: Function not implemented; this indicates that
154  *    the system is missing some functionality.
155  * @G_FILE_ERROR_FAILED: Does not correspond to a UNIX error code; this
156  *    is the standard "failed for unspecified reason" error code present
157  *    in all #GError error code enumerations. Returned if no specific
158  *    code applies.
159  *
160  * Values corresponding to @errno codes returned from file operations
161  * on UNIX. Unlike @errno codes, GFileError values are available on
162  * all systems, even Windows. The exact meaning of each code depends
163  * on what sort of file operation you were performing; the UNIX
164  * documentation gives more details. The following error code descriptions
165  * come from the GNU C Library manual, and are under the copyright
166  * of that manual.
167  *
168  * It's not very portable to make detailed assumptions about exactly
169  * which errors will be returned from a given operation. Some errors
170  * don't occur on some systems, etc., sometimes there are subtle
171  * differences in when a system will report a given error, etc.
172  */
173
174 /**
175  * G_FILE_ERROR:
176  *
177  * Error domain for file operations. Errors in this domain will
178  * be from the #GFileError enumeration. See #GError for information
179  * on error domains.
180  */
181
182 /**
183  * GFileTest:
184  * @G_FILE_TEST_IS_REGULAR: %TRUE if the file is a regular file
185  *     (not a directory). Note that this test will also return %TRUE
186  *     if the tested file is a symlink to a regular file.
187  * @G_FILE_TEST_IS_SYMLINK: %TRUE if the file is a symlink.
188  * @G_FILE_TEST_IS_DIR: %TRUE if the file is a directory.
189  * @G_FILE_TEST_IS_EXECUTABLE: %TRUE if the file is executable.
190  * @G_FILE_TEST_EXISTS: %TRUE if the file exists. It may or may not
191  *     be a regular file.
192  *
193  * A test to perform on a file using g_file_test().
194  */
195
196 /**
197  * g_mkdir_with_parents:
198  * @pathname: a pathname in the GLib file name encoding
199  * @mode: permissions to use for newly created directories
200  *
201  * Create a directory if it doesn't already exist. Create intermediate
202  * parent directories as needed, too.
203  *
204  * Returns: 0 if the directory already exists, or was successfully
205  * created. Returns -1 if an error occurred, with errno set.
206  *
207  * Since: 2.8
208  */
209 int
210 g_mkdir_with_parents (const gchar *pathname,
211                       int          mode)
212 {
213   gchar *fn, *p;
214
215   if (pathname == NULL || *pathname == '\0')
216     {
217       errno = EINVAL;
218       return -1;
219     }
220
221   fn = g_strdup (pathname);
222
223   if (g_path_is_absolute (fn))
224     p = (gchar *) g_path_skip_root (fn);
225   else
226     p = fn;
227
228   do
229     {
230       while (*p && !G_IS_DIR_SEPARATOR (*p))
231         p++;
232       
233       if (!*p)
234         p = NULL;
235       else
236         *p = '\0';
237       
238       if (!g_file_test (fn, G_FILE_TEST_EXISTS))
239         {
240           if (g_mkdir (fn, mode) == -1 && errno != EEXIST)
241             {
242               int errno_save = errno;
243               g_free (fn);
244               errno = errno_save;
245               return -1;
246             }
247         }
248       else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
249         {
250           g_free (fn);
251           errno = ENOTDIR;
252           return -1;
253         }
254       if (p)
255         {
256           *p++ = G_DIR_SEPARATOR;
257           while (*p && G_IS_DIR_SEPARATOR (*p))
258             p++;
259         }
260     }
261   while (p);
262
263   g_free (fn);
264
265   return 0;
266 }
267
268 /**
269  * g_file_test:
270  * @filename: a filename to test in the GLib file name encoding
271  * @test: bitfield of #GFileTest flags
272  * 
273  * Returns %TRUE if any of the tests in the bitfield @test are
274  * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS | 
275  * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists; 
276  * the check whether it's a directory doesn't matter since the existence 
277  * test is %TRUE. With the current set of available tests, there's no point
278  * passing in more than one test at a time.
279  * 
280  * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
281  * so for a symbolic link to a regular file g_file_test() will return
282  * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
283  *
284  * Note, that for a dangling symbolic link g_file_test() will return
285  * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
286  *
287  * You should never use g_file_test() to test whether it is safe
288  * to perform an operation, because there is always the possibility
289  * of the condition changing before you actually perform the operation.
290  * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
291  * to know whether it is safe to write to a file without being
292  * tricked into writing into a different location. It doesn't work!
293  * |[
294  * /&ast; DON'T DO THIS &ast;/
295  *  if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) 
296  *    {
297  *      fd = g_open (filename, O_WRONLY);
298  *      /&ast; write to fd &ast;/
299  *    }
300  * ]|
301  *
302  * Another thing to note is that %G_FILE_TEST_EXISTS and
303  * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
304  * system call. This usually doesn't matter, but if your program
305  * is setuid or setgid it means that these tests will give you
306  * the answer for the real user ID and group ID, rather than the
307  * effective user ID and group ID.
308  *
309  * On Windows, there are no symlinks, so testing for
310  * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
311  * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
312  * its name indicates that it is executable, checking for well-known
313  * extensions and those listed in the <envar>PATHEXT</envar> environment variable.
314  *
315  * Return value: whether a test was %TRUE
316  **/
317 gboolean
318 g_file_test (const gchar *filename,
319              GFileTest    test)
320 {
321 #ifdef G_OS_WIN32
322 /* stuff missing in std vc6 api */
323 #  ifndef INVALID_FILE_ATTRIBUTES
324 #    define INVALID_FILE_ATTRIBUTES -1
325 #  endif
326 #  ifndef FILE_ATTRIBUTE_DEVICE
327 #    define FILE_ATTRIBUTE_DEVICE 64
328 #  endif
329   int attributes;
330   wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
331
332   if (wfilename == NULL)
333     return FALSE;
334
335   attributes = GetFileAttributesW (wfilename);
336
337   g_free (wfilename);
338
339   if (attributes == INVALID_FILE_ATTRIBUTES)
340     return FALSE;
341
342   if (test & G_FILE_TEST_EXISTS)
343     return TRUE;
344       
345   if (test & G_FILE_TEST_IS_REGULAR)
346     {
347       if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0)
348         return TRUE;
349     }
350
351   if (test & G_FILE_TEST_IS_DIR)
352     {
353       if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
354         return TRUE;
355     }
356
357   /* "while" so that we can exit this "loop" with a simple "break" */
358   while (test & G_FILE_TEST_IS_EXECUTABLE)
359     {
360       const gchar *lastdot = strrchr (filename, '.');
361       const gchar *pathext = NULL, *p;
362       int extlen;
363
364       if (lastdot == NULL)
365         break;
366
367       if (_stricmp (lastdot, ".exe") == 0 ||
368           _stricmp (lastdot, ".cmd") == 0 ||
369           _stricmp (lastdot, ".bat") == 0 ||
370           _stricmp (lastdot, ".com") == 0)
371         return TRUE;
372
373       /* Check if it is one of the types listed in %PATHEXT% */
374
375       pathext = g_getenv ("PATHEXT");
376       if (pathext == NULL)
377         break;
378
379       pathext = g_utf8_casefold (pathext, -1);
380
381       lastdot = g_utf8_casefold (lastdot, -1);
382       extlen = strlen (lastdot);
383
384       p = pathext;
385       while (TRUE)
386         {
387           const gchar *q = strchr (p, ';');
388           if (q == NULL)
389             q = p + strlen (p);
390           if (extlen == q - p &&
391               memcmp (lastdot, p, extlen) == 0)
392             {
393               g_free ((gchar *) pathext);
394               g_free ((gchar *) lastdot);
395               return TRUE;
396             }
397           if (*q)
398             p = q + 1;
399           else
400             break;
401         }
402
403       g_free ((gchar *) pathext);
404       g_free ((gchar *) lastdot);
405       break;
406     }
407
408   return FALSE;
409 #else
410   if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
411     return TRUE;
412   
413   if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
414     {
415       if (getuid () != 0)
416         return TRUE;
417
418       /* For root, on some POSIX systems, access (filename, X_OK)
419        * will succeed even if no executable bits are set on the
420        * file. We fall through to a stat test to avoid that.
421        */
422     }
423   else
424     test &= ~G_FILE_TEST_IS_EXECUTABLE;
425
426   if (test & G_FILE_TEST_IS_SYMLINK)
427     {
428       struct stat s;
429
430       if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
431         return TRUE;
432     }
433   
434   if (test & (G_FILE_TEST_IS_REGULAR |
435               G_FILE_TEST_IS_DIR |
436               G_FILE_TEST_IS_EXECUTABLE))
437     {
438       struct stat s;
439       
440       if (stat (filename, &s) == 0)
441         {
442           if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
443             return TRUE;
444           
445           if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
446             return TRUE;
447
448           /* The extra test for root when access (file, X_OK) succeeds.
449            */
450           if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
451               ((s.st_mode & S_IXOTH) ||
452                (s.st_mode & S_IXUSR) ||
453                (s.st_mode & S_IXGRP)))
454             return TRUE;
455         }
456     }
457
458   return FALSE;
459 #endif
460 }
461
462 G_DEFINE_QUARK (g-file-error-quark, g_file_error)
463
464 /**
465  * g_file_error_from_errno:
466  * @err_no: an "errno" value
467  * 
468  * Gets a #GFileError constant based on the passed-in @err_no.
469  * For example, if you pass in <literal>EEXIST</literal> this function returns
470  * #G_FILE_ERROR_EXIST. Unlike <literal>errno</literal> values, you can portably
471  * assume that all #GFileError values will exist.
472  *
473  * Normally a #GFileError value goes into a #GError returned
474  * from a function that manipulates files. So you would use
475  * g_file_error_from_errno() when constructing a #GError.
476  * 
477  * Return value: #GFileError corresponding to the given @errno
478  **/
479 GFileError
480 g_file_error_from_errno (gint err_no)
481 {
482   switch (err_no)
483     {
484 #ifdef EEXIST
485     case EEXIST:
486       return G_FILE_ERROR_EXIST;
487 #endif
488
489 #ifdef EISDIR
490     case EISDIR:
491       return G_FILE_ERROR_ISDIR;
492 #endif
493
494 #ifdef EACCES
495     case EACCES:
496       return G_FILE_ERROR_ACCES;
497 #endif
498
499 #ifdef ENAMETOOLONG
500     case ENAMETOOLONG:
501       return G_FILE_ERROR_NAMETOOLONG;
502 #endif
503
504 #ifdef ENOENT
505     case ENOENT:
506       return G_FILE_ERROR_NOENT;
507 #endif
508
509 #ifdef ENOTDIR
510     case ENOTDIR:
511       return G_FILE_ERROR_NOTDIR;
512 #endif
513
514 #ifdef ENXIO
515     case ENXIO:
516       return G_FILE_ERROR_NXIO;
517 #endif
518
519 #ifdef ENODEV
520     case ENODEV:
521       return G_FILE_ERROR_NODEV;
522 #endif
523
524 #ifdef EROFS
525     case EROFS:
526       return G_FILE_ERROR_ROFS;
527 #endif
528
529 #ifdef ETXTBSY
530     case ETXTBSY:
531       return G_FILE_ERROR_TXTBSY;
532 #endif
533
534 #ifdef EFAULT
535     case EFAULT:
536       return G_FILE_ERROR_FAULT;
537 #endif
538
539 #ifdef ELOOP
540     case ELOOP:
541       return G_FILE_ERROR_LOOP;
542 #endif
543
544 #ifdef ENOSPC
545     case ENOSPC:
546       return G_FILE_ERROR_NOSPC;
547 #endif
548
549 #ifdef ENOMEM
550     case ENOMEM:
551       return G_FILE_ERROR_NOMEM;
552 #endif
553
554 #ifdef EMFILE
555     case EMFILE:
556       return G_FILE_ERROR_MFILE;
557 #endif
558
559 #ifdef ENFILE
560     case ENFILE:
561       return G_FILE_ERROR_NFILE;
562 #endif
563
564 #ifdef EBADF
565     case EBADF:
566       return G_FILE_ERROR_BADF;
567 #endif
568
569 #ifdef EINVAL
570     case EINVAL:
571       return G_FILE_ERROR_INVAL;
572 #endif
573
574 #ifdef EPIPE
575     case EPIPE:
576       return G_FILE_ERROR_PIPE;
577 #endif
578
579 #ifdef EAGAIN
580     case EAGAIN:
581       return G_FILE_ERROR_AGAIN;
582 #endif
583
584 #ifdef EINTR
585     case EINTR:
586       return G_FILE_ERROR_INTR;
587 #endif
588
589 #ifdef EIO
590     case EIO:
591       return G_FILE_ERROR_IO;
592 #endif
593
594 #ifdef EPERM
595     case EPERM:
596       return G_FILE_ERROR_PERM;
597 #endif
598
599 #ifdef ENOSYS
600     case ENOSYS:
601       return G_FILE_ERROR_NOSYS;
602 #endif
603
604     default:
605       return G_FILE_ERROR_FAILED;
606     }
607 }
608
609 static gboolean
610 get_contents_stdio (const gchar  *display_filename,
611                     FILE         *f,
612                     gchar       **contents,
613                     gsize        *length,
614                     GError      **error)
615 {
616   gchar buf[4096];
617   gsize bytes;
618   gchar *str = NULL;
619   gsize total_bytes = 0;
620   gsize total_allocated = 0;
621   gchar *tmp;
622
623   g_assert (f != NULL);
624
625   while (!feof (f))
626     {
627       gint save_errno;
628
629       bytes = fread (buf, 1, sizeof (buf), f);
630       save_errno = errno;
631
632       while ((total_bytes + bytes + 1) > total_allocated)
633         {
634           if (str)
635             total_allocated *= 2;
636           else
637             total_allocated = MIN (bytes + 1, sizeof (buf));
638
639           tmp = g_try_realloc (str, total_allocated);
640
641           if (tmp == NULL)
642             {
643               g_set_error (error,
644                            G_FILE_ERROR,
645                            G_FILE_ERROR_NOMEM,
646                            g_dngettext (GETTEXT_PACKAGE, "Could not allocate %lu byte to read file \"%s\"", "Could not allocate %lu bytes to read file \"%s\"", (gulong)total_allocated),
647                            (gulong) total_allocated,
648                            display_filename);
649
650               goto error;
651             }
652
653           str = tmp;
654         }
655
656       if (ferror (f))
657         {
658           g_set_error (error,
659                        G_FILE_ERROR,
660                        g_file_error_from_errno (save_errno),
661                        _("Error reading file '%s': %s"),
662                        display_filename,
663                        g_strerror (save_errno));
664
665           goto error;
666         }
667
668       memcpy (str + total_bytes, buf, bytes);
669
670       if (total_bytes + bytes < total_bytes) 
671         {
672           g_set_error (error,
673                        G_FILE_ERROR,
674                        G_FILE_ERROR_FAILED,
675                        _("File \"%s\" is too large"),
676                        display_filename);
677
678           goto error;
679         }
680
681       total_bytes += bytes;
682     }
683
684   fclose (f);
685
686   if (total_allocated == 0)
687     {
688       str = g_new (gchar, 1);
689       total_bytes = 0;
690     }
691
692   str[total_bytes] = '\0';
693
694   if (length)
695     *length = total_bytes;
696
697   *contents = str;
698
699   return TRUE;
700
701  error:
702
703   g_free (str);
704   fclose (f);
705
706   return FALSE;
707 }
708
709 #ifndef G_OS_WIN32
710
711 static gboolean
712 get_contents_regfile (const gchar  *display_filename,
713                       struct stat  *stat_buf,
714                       gint          fd,
715                       gchar       **contents,
716                       gsize        *length,
717                       GError      **error)
718 {
719   gchar *buf;
720   gsize bytes_read;
721   gsize size;
722   gsize alloc_size;
723   
724   size = stat_buf->st_size;
725
726   alloc_size = size + 1;
727   buf = g_try_malloc (alloc_size);
728
729   if (buf == NULL)
730     {
731       g_set_error (error,
732                    G_FILE_ERROR,
733                    G_FILE_ERROR_NOMEM,
734                            g_dngettext (GETTEXT_PACKAGE, "Could not allocate %lu byte to read file \"%s\"", "Could not allocate %lu bytes to read file \"%s\"", (gulong)alloc_size),
735                    (gulong) alloc_size, 
736                    display_filename);
737
738       goto error;
739     }
740   
741   bytes_read = 0;
742   while (bytes_read < size)
743     {
744       gssize rc;
745           
746       rc = read (fd, buf + bytes_read, size - bytes_read);
747
748       if (rc < 0)
749         {
750           if (errno != EINTR) 
751             {
752               int save_errno = errno;
753
754               g_free (buf);
755               g_set_error (error,
756                            G_FILE_ERROR,
757                            g_file_error_from_errno (save_errno),
758                            _("Failed to read from file '%s': %s"),
759                            display_filename, 
760                            g_strerror (save_errno));
761
762               goto error;
763             }
764         }
765       else if (rc == 0)
766         break;
767       else
768         bytes_read += rc;
769     }
770       
771   buf[bytes_read] = '\0';
772
773   if (length)
774     *length = bytes_read;
775   
776   *contents = buf;
777
778   close (fd);
779
780   return TRUE;
781
782  error:
783
784   close (fd);
785   
786   return FALSE;
787 }
788
789 static gboolean
790 get_contents_posix (const gchar  *filename,
791                     gchar       **contents,
792                     gsize        *length,
793                     GError      **error)
794 {
795   struct stat stat_buf;
796   gint fd;
797   gchar *display_filename = g_filename_display_name (filename);
798
799   /* O_BINARY useful on Cygwin */
800   fd = open (filename, O_RDONLY|O_BINARY);
801
802   if (fd < 0)
803     {
804       int save_errno = errno;
805
806       g_set_error (error,
807                    G_FILE_ERROR,
808                    g_file_error_from_errno (save_errno),
809                    _("Failed to open file '%s': %s"),
810                    display_filename, 
811                    g_strerror (save_errno));
812       g_free (display_filename);
813
814       return FALSE;
815     }
816
817   /* I don't think this will ever fail, aside from ENOMEM, but. */
818   if (fstat (fd, &stat_buf) < 0)
819     {
820       int save_errno = errno;
821
822       close (fd);
823       g_set_error (error,
824                    G_FILE_ERROR,
825                    g_file_error_from_errno (save_errno),
826                    _("Failed to get attributes of file '%s': fstat() failed: %s"),
827                    display_filename, 
828                    g_strerror (save_errno));
829       g_free (display_filename);
830
831       return FALSE;
832     }
833
834   if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
835     {
836       gboolean retval = get_contents_regfile (display_filename,
837                                               &stat_buf,
838                                               fd,
839                                               contents,
840                                               length,
841                                               error);
842       g_free (display_filename);
843
844       return retval;
845     }
846   else
847     {
848       FILE *f;
849       gboolean retval;
850
851       f = fdopen (fd, "r");
852       
853       if (f == NULL)
854         {
855           int save_errno = errno;
856
857           g_set_error (error,
858                        G_FILE_ERROR,
859                        g_file_error_from_errno (save_errno),
860                        _("Failed to open file '%s': fdopen() failed: %s"),
861                        display_filename, 
862                        g_strerror (save_errno));
863           g_free (display_filename);
864
865           return FALSE;
866         }
867   
868       retval = get_contents_stdio (display_filename, f, contents, length, error);
869       g_free (display_filename);
870
871       return retval;
872     }
873 }
874
875 #else  /* G_OS_WIN32 */
876
877 static gboolean
878 get_contents_win32 (const gchar  *filename,
879                     gchar       **contents,
880                     gsize        *length,
881                     GError      **error)
882 {
883   FILE *f;
884   gboolean retval;
885   gchar *display_filename = g_filename_display_name (filename);
886   int save_errno;
887   
888   f = g_fopen (filename, "rb");
889   save_errno = errno;
890
891   if (f == NULL)
892     {
893       g_set_error (error,
894                    G_FILE_ERROR,
895                    g_file_error_from_errno (save_errno),
896                    _("Failed to open file '%s': %s"),
897                    display_filename,
898                    g_strerror (save_errno));
899       g_free (display_filename);
900
901       return FALSE;
902     }
903   
904   retval = get_contents_stdio (display_filename, f, contents, length, error);
905   g_free (display_filename);
906
907   return retval;
908 }
909
910 #endif
911
912 /**
913  * g_file_get_contents:
914  * @filename: (type filename): name of a file to read contents from, in the GLib file name encoding
915  * @contents: (out) (array length=length) (element-type guint8): location to store an allocated string, use g_free() to free
916  *     the returned string
917  * @length: (allow-none): location to store length in bytes of the contents, or %NULL
918  * @error: return location for a #GError, or %NULL
919  *
920  * Reads an entire file into allocated memory, with good error
921  * checking.
922  *
923  * If the call was successful, it returns %TRUE and sets @contents to the file
924  * contents and @length to the length of the file contents in bytes. The string
925  * stored in @contents will be nul-terminated, so for text files you can pass
926  * %NULL for the @length argument. If the call was not successful, it returns
927  * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
928  * codes are those in the #GFileError enumeration. In the error case,
929  * @contents is set to %NULL and @length is set to zero.
930  *
931  * Return value: %TRUE on success, %FALSE if an error occurred
932  **/
933 gboolean
934 g_file_get_contents (const gchar  *filename,
935                      gchar       **contents,
936                      gsize        *length,
937                      GError      **error)
938 {  
939   g_return_val_if_fail (filename != NULL, FALSE);
940   g_return_val_if_fail (contents != NULL, FALSE);
941
942   *contents = NULL;
943   if (length)
944     *length = 0;
945
946 #ifdef G_OS_WIN32
947   return get_contents_win32 (filename, contents, length, error);
948 #else
949   return get_contents_posix (filename, contents, length, error);
950 #endif
951 }
952
953 static gboolean
954 rename_file (const char  *old_name,
955              const char  *new_name,
956              GError     **err)
957 {
958   errno = 0;
959   if (g_rename (old_name, new_name) == -1)
960     {
961       int save_errno = errno;
962       gchar *display_old_name = g_filename_display_name (old_name);
963       gchar *display_new_name = g_filename_display_name (new_name);
964
965       g_set_error (err,
966                    G_FILE_ERROR,
967                    g_file_error_from_errno (save_errno),
968                    _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
969                    display_old_name,
970                    display_new_name,
971                    g_strerror (save_errno));
972
973       g_free (display_old_name);
974       g_free (display_new_name);
975       
976       return FALSE;
977     }
978   
979   return TRUE;
980 }
981
982 static char *
983 format_error_message (const gchar  *filename,
984                       const gchar  *format_string) G_GNUC_FORMAT(2);
985
986 #pragma GCC diagnostic push
987 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
988
989 static char *
990 format_error_message (const gchar  *filename,
991                       const gchar  *format_string)
992 {
993   gint saved_errno = errno;
994   gchar *display_name;
995   gchar *msg;
996
997   display_name = g_filename_display_name (filename);
998   msg = g_strdup_printf (format_string, display_name, g_strerror (saved_errno));
999   g_free (display_name);
1000
1001   return msg;
1002 }
1003
1004 #pragma GCC diagnostic pop
1005
1006 /* format string must have two '%s':
1007  *
1008  *   - the place for the filename
1009  *   - the place for the strerror
1010  */
1011 static void
1012 set_file_error (GError      **error,
1013                 const gchar  *filename,
1014                 const gchar  *format_string)
1015                       
1016 {
1017   int saved_errno = errno;
1018   char *msg = format_error_message (filename, format_string);
1019
1020   g_set_error_literal (error, G_FILE_ERROR, g_file_error_from_errno (saved_errno),
1021                        msg);
1022   g_free (msg);
1023 }
1024
1025 static gchar *
1026 write_to_temp_file (const gchar  *contents,
1027                     gssize        length,
1028                     const gchar  *dest_file,
1029                     GError      **err)
1030 {
1031   gchar *tmp_name;
1032   gchar *retval;
1033   gint fd;
1034
1035   retval = NULL;
1036
1037   tmp_name = g_strdup_printf ("%s.XXXXXX", dest_file);
1038
1039   errno = 0;
1040   fd = g_mkstemp_full (tmp_name, O_RDWR | O_BINARY, 0666);
1041
1042   if (fd == -1)
1043     {
1044       set_file_error (err, tmp_name, _("Failed to create file '%s': %s"));
1045       goto out;
1046     }
1047
1048 #ifdef HAVE_FALLOCATE
1049   if (length > 0)
1050     {
1051       /* We do this on a 'best effort' basis... It may not be supported
1052        * on the underlying filesystem.
1053        */
1054       (void) fallocate (fd, 0, 0, length);
1055     }
1056 #endif
1057   while (length > 0)
1058     {
1059       gssize s;
1060
1061       s = write (fd, contents, length);
1062
1063       if (s < 0)
1064         {
1065           if (errno == EINTR)
1066             continue;
1067
1068           set_file_error (err, tmp_name, _("Failed to write file '%s': write() failed: %s"));
1069           close (fd);
1070           g_unlink (tmp_name);
1071
1072           goto out;
1073         }
1074
1075       g_assert (s <= length);
1076
1077       contents += s;
1078       length -= s;
1079     }
1080
1081 #ifdef BTRFS_SUPER_MAGIC
1082   {
1083     struct statfs buf;
1084
1085     /* On Linux, on btrfs, skip the fsync since rename-over-existing is
1086      * guaranteed to be atomic and this is the only case in which we
1087      * would fsync() anyway.
1088      */
1089
1090     if (fstatfs (fd, &buf) == 0 && buf.f_type == BTRFS_SUPER_MAGIC)
1091       goto no_fsync;
1092   }
1093 #endif
1094
1095 #ifdef HAVE_FSYNC
1096   {
1097     struct stat statbuf;
1098
1099     errno = 0;
1100     /* If the final destination exists and is > 0 bytes, we want to sync the
1101      * newly written file to ensure the data is on disk when we rename over
1102      * the destination. Otherwise if we get a system crash we can lose both
1103      * the new and the old file on some filesystems. (I.E. those that don't
1104      * guarantee the data is written to the disk before the metadata.)
1105      */
1106     if (g_lstat (dest_file, &statbuf) == 0 && statbuf.st_size > 0 && fsync (fd) != 0)
1107       {
1108         set_file_error (err, tmp_name, _("Failed to write file '%s': fsync() failed: %s"));
1109         close (fd);
1110         g_unlink (tmp_name);
1111
1112         goto out;
1113       }
1114   }
1115 #endif
1116
1117 #ifdef BTRFS_SUPER_MAGIC
1118  no_fsync:
1119 #endif
1120
1121   errno = 0;
1122   if (!g_close (fd, err))
1123     {
1124       g_unlink (tmp_name);
1125
1126       goto out;
1127     }
1128
1129   retval = g_strdup (tmp_name);
1130
1131  out:
1132   g_free (tmp_name);
1133
1134   return retval;
1135 }
1136
1137 /**
1138  * g_file_set_contents:
1139  * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1140  *   encoding
1141  * @contents: (array length=length) (element-type guint8): string to write to the file
1142  * @length: length of @contents, or -1 if @contents is a nul-terminated string
1143  * @error: return location for a #GError, or %NULL
1144  *
1145  * Writes all of @contents to a file named @filename, with good error checking.
1146  * If a file called @filename already exists it will be overwritten.
1147  *
1148  * This write is atomic in the sense that it is first written to a temporary
1149  * file which is then renamed to the final name. Notes:
1150  * <itemizedlist>
1151  * <listitem>
1152  *    On Unix, if @filename already exists hard links to @filename will break.
1153  *    Also since the file is recreated, existing permissions, access control
1154  *    lists, metadata etc. may be lost. If @filename is a symbolic link,
1155  *    the link itself will be replaced, not the linked file.
1156  * </listitem>
1157  * <listitem>
1158  *   On Windows renaming a file will not remove an existing file with the
1159  *   new name, so on Windows there is a race condition between the existing
1160  *   file being removed and the temporary file being renamed.
1161  * </listitem>
1162  * <listitem>
1163  *   On Windows there is no way to remove a file that is open to some
1164  *   process, or mapped into memory. Thus, this function will fail if
1165  *   @filename already exists and is open.
1166  * </listitem>
1167  * </itemizedlist>
1168  *
1169  * If the call was successful, it returns %TRUE. If the call was not successful,
1170  * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1171  * Possible error codes are those in the #GFileError enumeration.
1172  *
1173  * Note that the name for the temporary file is constructed by appending up
1174  * to 7 characters to @filename.
1175  *
1176  * Return value: %TRUE on success, %FALSE if an error occurred
1177  *
1178  * Since: 2.8
1179  **/
1180 gboolean
1181 g_file_set_contents (const gchar  *filename,
1182                      const gchar  *contents,
1183                      gssize        length,
1184                      GError      **error)
1185 {
1186   gchar *tmp_filename;
1187   gboolean retval;
1188   GError *rename_error = NULL;
1189   
1190   g_return_val_if_fail (filename != NULL, FALSE);
1191   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1192   g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1193   g_return_val_if_fail (length >= -1, FALSE);
1194   
1195   if (length == -1)
1196     length = strlen (contents);
1197
1198   tmp_filename = write_to_temp_file (contents, length, filename, error);
1199   
1200   if (!tmp_filename)
1201     {
1202       retval = FALSE;
1203       goto out;
1204     }
1205
1206   if (!rename_file (tmp_filename, filename, &rename_error))
1207     {
1208 #ifndef G_OS_WIN32
1209
1210       g_unlink (tmp_filename);
1211       g_propagate_error (error, rename_error);
1212       retval = FALSE;
1213       goto out;
1214
1215 #else /* G_OS_WIN32 */
1216       
1217       /* Renaming failed, but on Windows this may just mean
1218        * the file already exists. So if the target file
1219        * exists, try deleting it and do the rename again.
1220        */
1221       if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1222         {
1223           g_unlink (tmp_filename);
1224           g_propagate_error (error, rename_error);
1225           retval = FALSE;
1226           goto out;
1227         }
1228
1229       g_error_free (rename_error);
1230       
1231       if (g_unlink (filename) == -1)
1232         {
1233           gchar *display_filename = g_filename_display_name (filename);
1234
1235           int save_errno = errno;
1236           
1237           g_set_error (error,
1238                        G_FILE_ERROR,
1239                        g_file_error_from_errno (save_errno),
1240                        _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1241                        display_filename,
1242                        g_strerror (save_errno));
1243
1244           g_free (display_filename);
1245           g_unlink (tmp_filename);
1246           retval = FALSE;
1247           goto out;
1248         }
1249       
1250       if (!rename_file (tmp_filename, filename, error))
1251         {
1252           g_unlink (tmp_filename);
1253           retval = FALSE;
1254           goto out;
1255         }
1256
1257 #endif
1258     }
1259
1260   retval = TRUE;
1261   
1262  out:
1263   g_free (tmp_filename);
1264   return retval;
1265 }
1266
1267 /*
1268  * get_tmp_file based on the mkstemp implementation from the GNU C library.
1269  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1270  */
1271 typedef gint (*GTmpFileCallback) (const gchar *, gint, gint);
1272
1273 static gint
1274 get_tmp_file (gchar            *tmpl,
1275               GTmpFileCallback  f,
1276               int               flags,
1277               int               mode)
1278 {
1279   char *XXXXXX;
1280   int count, fd;
1281   static const char letters[] =
1282     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1283   static const int NLETTERS = sizeof (letters) - 1;
1284   glong value;
1285   GTimeVal tv;
1286   static int counter = 0;
1287
1288   g_return_val_if_fail (tmpl != NULL, -1);
1289
1290   /* find the last occurrence of "XXXXXX" */
1291   XXXXXX = g_strrstr (tmpl, "XXXXXX");
1292
1293   if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1294     {
1295       errno = EINVAL;
1296       return -1;
1297     }
1298
1299   /* Get some more or less random data.  */
1300   g_get_current_time (&tv);
1301   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1302
1303   for (count = 0; count < 100; value += 7777, ++count)
1304     {
1305       glong v = value;
1306
1307       /* Fill in the random bits.  */
1308       XXXXXX[0] = letters[v % NLETTERS];
1309       v /= NLETTERS;
1310       XXXXXX[1] = letters[v % NLETTERS];
1311       v /= NLETTERS;
1312       XXXXXX[2] = letters[v % NLETTERS];
1313       v /= NLETTERS;
1314       XXXXXX[3] = letters[v % NLETTERS];
1315       v /= NLETTERS;
1316       XXXXXX[4] = letters[v % NLETTERS];
1317       v /= NLETTERS;
1318       XXXXXX[5] = letters[v % NLETTERS];
1319
1320       fd = f (tmpl, flags, mode);
1321
1322       if (fd >= 0)
1323         return fd;
1324       else if (errno != EEXIST)
1325         /* Any other error will apply also to other names we might
1326          *  try, and there are 2^32 or so of them, so give up now.
1327          */
1328         return -1;
1329     }
1330
1331   /* We got out of the loop because we ran out of combinations to try.  */
1332   errno = EEXIST;
1333   return -1;
1334 }
1335
1336 /* Some GTmpFileCallback implementations.
1337  *
1338  * Note: we cannot use open() or g_open() directly because even though
1339  * they appear compatible, they may be vararg functions and calling
1340  * varargs functions through a non-varargs type is undefined.
1341  */
1342 static gint
1343 wrap_g_mkdir (const gchar *filename,
1344               int          flags G_GNUC_UNUSED,
1345               int          mode)
1346 {
1347   /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1348   return g_mkdir (filename, mode);
1349 }
1350
1351 static gint
1352 wrap_g_open (const gchar *filename,
1353                 int          flags,
1354                 int          mode)
1355 {
1356   return g_open (filename, flags, mode);
1357 }
1358
1359 /**
1360  * g_mkdtemp_full:
1361  * @tmpl: (type filename): template directory name
1362  * @mode: permissions to create the temporary directory with
1363  *
1364  * Creates a temporary directory. See the mkdtemp() documentation
1365  * on most UNIX-like systems.
1366  *
1367  * The parameter is a string that should follow the rules for
1368  * mkdtemp() templates, i.e. contain the string "XXXXXX".
1369  * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1370  * sequence does not have to occur at the very end of the template
1371  * and you can pass a @mode. The X string will be modified to form
1372  * the name of a directory that didn't exist. The string should be
1373  * in the GLib file name encoding. Most importantly, on Windows it
1374  * should be in UTF-8.
1375  *
1376  * Return value: A pointer to @tmpl, which has been modified
1377  *     to hold the directory name. In case of errors, %NULL is
1378  *     returned, and %errno will be set.
1379  *
1380  * Since: 2.30
1381  */
1382 gchar *
1383 g_mkdtemp_full (gchar *tmpl,
1384                 gint   mode)
1385 {
1386   if (get_tmp_file (tmpl, wrap_g_mkdir, 0, mode) == -1)
1387     return NULL;
1388   else
1389     return tmpl;
1390 }
1391
1392 /**
1393  * g_mkdtemp:
1394  * @tmpl: (type filename): template directory name
1395  *
1396  * Creates a temporary directory. See the mkdtemp() documentation
1397  * on most UNIX-like systems.
1398  *
1399  * The parameter is a string that should follow the rules for
1400  * mkdtemp() templates, i.e. contain the string "XXXXXX".
1401  * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1402  * sequence does not have to occur at the very end of the template
1403  * and you can pass a @mode and additional @flags. The X string will
1404  * be modified to form the name of a directory that didn't exist.
1405  * The string should be in the GLib file name encoding. Most importantly,
1406  * on Windows it should be in UTF-8.
1407  *
1408  * Return value: A pointer to @tmpl, which has been modified
1409  *     to hold the directory name.  In case of errors, %NULL is
1410  *     returned and %errno will be set.
1411  *
1412  * Since: 2.30
1413  */
1414 gchar *
1415 g_mkdtemp (gchar *tmpl)
1416 {
1417   return g_mkdtemp_full (tmpl, 0700);
1418 }
1419
1420 /**
1421  * g_mkstemp_full:
1422  * @tmpl: (type filename): template filename
1423  * @flags: flags to pass to an open() call in addition to O_EXCL
1424  *     and O_CREAT, which are passed automatically
1425  * @mode: permissions to create the temporary file with
1426  *
1427  * Opens a temporary file. See the mkstemp() documentation
1428  * on most UNIX-like systems.
1429  *
1430  * The parameter is a string that should follow the rules for
1431  * mkstemp() templates, i.e. contain the string "XXXXXX".
1432  * g_mkstemp_full() is slightly more flexible than mkstemp()
1433  * in that the sequence does not have to occur at the very end of the
1434  * template and you can pass a @mode and additional @flags. The X
1435  * string will be modified to form the name of a file that didn't exist.
1436  * The string should be in the GLib file name encoding. Most importantly,
1437  * on Windows it should be in UTF-8.
1438  *
1439  * Return value: A file handle (as from open()) to the file
1440  *     opened for reading and writing. The file handle should be
1441  *     closed with close(). In case of errors, -1 is returned
1442  *     and %errno will be set.
1443  *
1444  * Since: 2.22
1445  */
1446 gint
1447 g_mkstemp_full (gchar *tmpl,
1448                 gint   flags,
1449                 gint   mode)
1450 {
1451   /* tmpl is in UTF-8 on Windows, thus use g_open() */
1452   return get_tmp_file (tmpl, wrap_g_open,
1453                        flags | O_CREAT | O_EXCL, mode);
1454 }
1455
1456 /**
1457  * g_mkstemp:
1458  * @tmpl: (type filename): template filename
1459  *
1460  * Opens a temporary file. See the mkstemp() documentation
1461  * on most UNIX-like systems.
1462  *
1463  * The parameter is a string that should follow the rules for
1464  * mkstemp() templates, i.e. contain the string "XXXXXX".
1465  * g_mkstemp() is slightly more flexible than mkstemp() in that the
1466  * sequence does not have to occur at the very end of the template.
1467  * The X string will be modified to form the name of a file that
1468  * didn't exist. The string should be in the GLib file name encoding.
1469  * Most importantly, on Windows it should be in UTF-8.
1470  *
1471  * Return value: A file handle (as from open()) to the file
1472  *     opened for reading and writing. The file is opened in binary
1473  *     mode on platforms where there is a difference. The file handle
1474  *     should be closed with close(). In case of errors, -1 is
1475  *     returned and %errno will be set.
1476  */
1477 gint
1478 g_mkstemp (gchar *tmpl)
1479 {
1480   return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1481 }
1482
1483 static gint
1484 g_get_tmp_name (const gchar      *tmpl,
1485                 gchar           **name_used,
1486                 GTmpFileCallback  f,
1487                 gint              flags,
1488                 gint              mode,
1489                 GError          **error)
1490 {
1491   int retval;
1492   const char *tmpdir;
1493   const char *sep;
1494   char *fulltemplate;
1495   const char *slash;
1496
1497   if (tmpl == NULL)
1498     tmpl = ".XXXXXX";
1499
1500   if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1501 #ifdef G_OS_WIN32
1502       || (strchr (tmpl, '/') != NULL && (slash = "/"))
1503 #endif
1504       )
1505     {
1506       gchar *display_tmpl = g_filename_display_name (tmpl);
1507       char c[2];
1508       c[0] = *slash;
1509       c[1] = '\0';
1510
1511       g_set_error (error,
1512                    G_FILE_ERROR,
1513                    G_FILE_ERROR_FAILED,
1514                    _("Template '%s' invalid, should not contain a '%s'"),
1515                    display_tmpl, c);
1516       g_free (display_tmpl);
1517
1518       return -1;
1519     }
1520
1521   if (strstr (tmpl, "XXXXXX") == NULL)
1522     {
1523       gchar *display_tmpl = g_filename_display_name (tmpl);
1524       g_set_error (error,
1525                    G_FILE_ERROR,
1526                    G_FILE_ERROR_FAILED,
1527                    _("Template '%s' doesn't contain XXXXXX"),
1528                    display_tmpl);
1529       g_free (display_tmpl);
1530       return -1;
1531     }
1532
1533   tmpdir = g_get_tmp_dir ();
1534
1535   if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1536     sep = "";
1537   else
1538     sep = G_DIR_SEPARATOR_S;
1539
1540   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1541
1542   retval = get_tmp_file (fulltemplate, f, flags, mode);
1543   if (retval == -1)
1544     {
1545       int save_errno = errno;
1546       gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1547
1548       g_set_error (error,
1549                    G_FILE_ERROR,
1550                    g_file_error_from_errno (save_errno),
1551                    _("Failed to create file '%s': %s"),
1552                    display_fulltemplate, g_strerror (save_errno));
1553       g_free (display_fulltemplate);
1554       g_free (fulltemplate);
1555       return -1;
1556     }
1557
1558   *name_used = fulltemplate;
1559
1560   return retval;
1561 }
1562
1563 /**
1564  * g_file_open_tmp:
1565  * @tmpl: (type filename) (allow-none): Template for file name, as in
1566  *     g_mkstemp(), basename only, or %NULL for a default template
1567  * @name_used: (out) (type filename): location to store actual name used,
1568  *     or %NULL
1569  * @error: return location for a #GError
1570  *
1571  * Opens a file for writing in the preferred directory for temporary
1572  * files (as returned by g_get_tmp_dir()).
1573  *
1574  * @tmpl should be a string in the GLib file name encoding containing
1575  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1576  * However, unlike these functions, the template should only be a
1577  * basename, no directory components are allowed. If template is
1578  * %NULL, a default template is used.
1579  *
1580  * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
1581  * modified, and might thus be a read-only literal string.
1582  *
1583  * Upon success, and if @name_used is non-%NULL, the actual name used
1584  * is returned in @name_used. This string should be freed with g_free()
1585  * when not needed any longer. The returned name is in the GLib file
1586  * name encoding.
1587  *
1588  * Return value: A file handle (as from open()) to the file opened for
1589  *     reading and writing. The file is opened in binary mode on platforms
1590  *     where there is a difference. The file handle should be closed with
1591  *     close(). In case of errors, -1 is returned and @error will be set.
1592  */
1593 gint
1594 g_file_open_tmp (const gchar  *tmpl,
1595                  gchar       **name_used,
1596                  GError      **error)
1597 {
1598   gchar *fulltemplate;
1599   gint result;
1600
1601   result = g_get_tmp_name (tmpl, &fulltemplate,
1602                            wrap_g_open,
1603                            O_CREAT | O_EXCL | O_RDWR | O_BINARY,
1604                            0600,
1605                            error);
1606   if (result != -1)
1607     {
1608       if (name_used)
1609         *name_used = fulltemplate;
1610       else
1611         g_free (fulltemplate);
1612     }
1613
1614   return result;
1615 }
1616
1617 /**
1618  * g_dir_make_tmp:
1619  * @tmpl: (type filename) (allow-none): Template for directory name,
1620  *     as in g_mkdtemp(), basename only, or %NULL for a default template
1621  * @error: return location for a #GError
1622  *
1623  * Creates a subdirectory in the preferred directory for temporary
1624  * files (as returned by g_get_tmp_dir()).
1625  *
1626  * @tmpl should be a string in the GLib file name encoding containing
1627  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1628  * However, unlike these functions, the template should only be a
1629  * basename, no directory components are allowed. If template is
1630  * %NULL, a default template is used.
1631  *
1632  * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
1633  * modified, and might thus be a read-only literal string.
1634  *
1635  * Return value: (type filename): The actual name used. This string
1636  *     should be freed with g_free() when not needed any longer and is
1637  *     is in the GLib file name encoding. In case of errors, %NULL is
1638  *     returned and @error will be set.
1639  *
1640  * Since: 2.30
1641  */
1642 gchar *
1643 g_dir_make_tmp (const gchar  *tmpl,
1644                 GError      **error)
1645 {
1646   gchar *fulltemplate;
1647
1648   if (g_get_tmp_name (tmpl, &fulltemplate, wrap_g_mkdir, 0, 0700, error) == -1)
1649     return NULL;
1650   else
1651     return fulltemplate;
1652 }
1653
1654 static gchar *
1655 g_build_path_va (const gchar  *separator,
1656                  const gchar  *first_element,
1657                  va_list      *args,
1658                  gchar       **str_array)
1659 {
1660   GString *result;
1661   gint separator_len = strlen (separator);
1662   gboolean is_first = TRUE;
1663   gboolean have_leading = FALSE;
1664   const gchar *single_element = NULL;
1665   const gchar *next_element;
1666   const gchar *last_trailing = NULL;
1667   gint i = 0;
1668
1669   result = g_string_new (NULL);
1670
1671   if (str_array)
1672     next_element = str_array[i++];
1673   else
1674     next_element = first_element;
1675
1676   while (TRUE)
1677     {
1678       const gchar *element;
1679       const gchar *start;
1680       const gchar *end;
1681
1682       if (next_element)
1683         {
1684           element = next_element;
1685           if (str_array)
1686             next_element = str_array[i++];
1687           else
1688             next_element = va_arg (*args, gchar *);
1689         }
1690       else
1691         break;
1692
1693       /* Ignore empty elements */
1694       if (!*element)
1695         continue;
1696       
1697       start = element;
1698
1699       if (separator_len)
1700         {
1701           while (strncmp (start, separator, separator_len) == 0)
1702             start += separator_len;
1703         }
1704
1705       end = start + strlen (start);
1706       
1707       if (separator_len)
1708         {
1709           while (end >= start + separator_len &&
1710                  strncmp (end - separator_len, separator, separator_len) == 0)
1711             end -= separator_len;
1712           
1713           last_trailing = end;
1714           while (last_trailing >= element + separator_len &&
1715                  strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1716             last_trailing -= separator_len;
1717
1718           if (!have_leading)
1719             {
1720               /* If the leading and trailing separator strings are in the
1721                * same element and overlap, the result is exactly that element
1722                */
1723               if (last_trailing <= start)
1724                 single_element = element;
1725                   
1726               g_string_append_len (result, element, start - element);
1727               have_leading = TRUE;
1728             }
1729           else
1730             single_element = NULL;
1731         }
1732
1733       if (end == start)
1734         continue;
1735
1736       if (!is_first)
1737         g_string_append (result, separator);
1738       
1739       g_string_append_len (result, start, end - start);
1740       is_first = FALSE;
1741     }
1742
1743   if (single_element)
1744     {
1745       g_string_free (result, TRUE);
1746       return g_strdup (single_element);
1747     }
1748   else
1749     {
1750       if (last_trailing)
1751         g_string_append (result, last_trailing);
1752   
1753       return g_string_free (result, FALSE);
1754     }
1755 }
1756
1757 /**
1758  * g_build_pathv:
1759  * @separator: a string used to separator the elements of the path.
1760  * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
1761  * 
1762  * Behaves exactly like g_build_path(), but takes the path elements 
1763  * as a string array, instead of varargs. This function is mainly
1764  * meant for language bindings.
1765  *
1766  * Return value: a newly-allocated string that must be freed with g_free().
1767  *
1768  * Since: 2.8
1769  */
1770 gchar *
1771 g_build_pathv (const gchar  *separator,
1772                gchar       **args)
1773 {
1774   if (!args)
1775     return NULL;
1776
1777   return g_build_path_va (separator, NULL, NULL, args);
1778 }
1779
1780
1781 /**
1782  * g_build_path:
1783  * @separator: a string used to separator the elements of the path.
1784  * @first_element: the first element in the path
1785  * @...: remaining elements in path, terminated by %NULL
1786  * 
1787  * Creates a path from a series of elements using @separator as the
1788  * separator between elements. At the boundary between two elements,
1789  * any trailing occurrences of separator in the first element, or
1790  * leading occurrences of separator in the second element are removed
1791  * and exactly one copy of the separator is inserted.
1792  *
1793  * Empty elements are ignored.
1794  *
1795  * The number of leading copies of the separator on the result is
1796  * the same as the number of leading copies of the separator on
1797  * the first non-empty element.
1798  *
1799  * The number of trailing copies of the separator on the result is
1800  * the same as the number of trailing copies of the separator on
1801  * the last non-empty element. (Determination of the number of
1802  * trailing copies is done without stripping leading copies, so
1803  * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1804  * has 1 trailing copy.)
1805  *
1806  * However, if there is only a single non-empty element, and there
1807  * are no characters in that element not part of the leading or
1808  * trailing separators, then the result is exactly the original value
1809  * of that element.
1810  *
1811  * Other than for determination of the number of leading and trailing
1812  * copies of the separator, elements consisting only of copies
1813  * of the separator are ignored.
1814  * 
1815  * Return value: a newly-allocated string that must be freed with g_free().
1816  **/
1817 gchar *
1818 g_build_path (const gchar *separator,
1819               const gchar *first_element,
1820               ...)
1821 {
1822   gchar *str;
1823   va_list args;
1824
1825   g_return_val_if_fail (separator != NULL, NULL);
1826
1827   va_start (args, first_element);
1828   str = g_build_path_va (separator, first_element, &args, NULL);
1829   va_end (args);
1830
1831   return str;
1832 }
1833
1834 #ifdef G_OS_WIN32
1835
1836 static gchar *
1837 g_build_pathname_va (const gchar  *first_element,
1838                      va_list      *args,
1839                      gchar       **str_array)
1840 {
1841   /* Code copied from g_build_pathv(), and modified to use two
1842    * alternative single-character separators.
1843    */
1844   GString *result;
1845   gboolean is_first = TRUE;
1846   gboolean have_leading = FALSE;
1847   const gchar *single_element = NULL;
1848   const gchar *next_element;
1849   const gchar *last_trailing = NULL;
1850   gchar current_separator = '\\';
1851   gint i = 0;
1852
1853   result = g_string_new (NULL);
1854
1855   if (str_array)
1856     next_element = str_array[i++];
1857   else
1858     next_element = first_element;
1859   
1860   while (TRUE)
1861     {
1862       const gchar *element;
1863       const gchar *start;
1864       const gchar *end;
1865
1866       if (next_element)
1867         {
1868           element = next_element;
1869           if (str_array)
1870             next_element = str_array[i++];
1871           else
1872             next_element = va_arg (*args, gchar *);
1873         }
1874       else
1875         break;
1876
1877       /* Ignore empty elements */
1878       if (!*element)
1879         continue;
1880       
1881       start = element;
1882
1883       if (TRUE)
1884         {
1885           while (start &&
1886                  (*start == '\\' || *start == '/'))
1887             {
1888               current_separator = *start;
1889               start++;
1890             }
1891         }
1892
1893       end = start + strlen (start);
1894       
1895       if (TRUE)
1896         {
1897           while (end >= start + 1 &&
1898                  (end[-1] == '\\' || end[-1] == '/'))
1899             {
1900               current_separator = end[-1];
1901               end--;
1902             }
1903           
1904           last_trailing = end;
1905           while (last_trailing >= element + 1 &&
1906                  (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1907             last_trailing--;
1908
1909           if (!have_leading)
1910             {
1911               /* If the leading and trailing separator strings are in the
1912                * same element and overlap, the result is exactly that element
1913                */
1914               if (last_trailing <= start)
1915                 single_element = element;
1916                   
1917               g_string_append_len (result, element, start - element);
1918               have_leading = TRUE;
1919             }
1920           else
1921             single_element = NULL;
1922         }
1923
1924       if (end == start)
1925         continue;
1926
1927       if (!is_first)
1928         g_string_append_len (result, &current_separator, 1);
1929       
1930       g_string_append_len (result, start, end - start);
1931       is_first = FALSE;
1932     }
1933
1934   if (single_element)
1935     {
1936       g_string_free (result, TRUE);
1937       return g_strdup (single_element);
1938     }
1939   else
1940     {
1941       if (last_trailing)
1942         g_string_append (result, last_trailing);
1943   
1944       return g_string_free (result, FALSE);
1945     }
1946 }
1947
1948 #endif
1949
1950 /**
1951  * g_build_filenamev:
1952  * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
1953  * 
1954  * Behaves exactly like g_build_filename(), but takes the path elements 
1955  * as a string array, instead of varargs. This function is mainly
1956  * meant for language bindings.
1957  *
1958  * Return value: a newly-allocated string that must be freed with g_free().
1959  * 
1960  * Since: 2.8
1961  */
1962 gchar *
1963 g_build_filenamev (gchar **args)
1964 {
1965   gchar *str;
1966
1967 #ifndef G_OS_WIN32
1968   str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
1969 #else
1970   str = g_build_pathname_va (NULL, NULL, args);
1971 #endif
1972
1973   return str;
1974 }
1975
1976 /**
1977  * g_build_filename:
1978  * @first_element: the first element in the path
1979  * @...: remaining elements in path, terminated by %NULL
1980  * 
1981  * Creates a filename from a series of elements using the correct
1982  * separator for filenames.
1983  *
1984  * On Unix, this function behaves identically to <literal>g_build_path
1985  * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
1986  *
1987  * On Windows, it takes into account that either the backslash
1988  * (<literal>\</literal> or slash (<literal>/</literal>) can be used
1989  * as separator in filenames, but otherwise behaves as on Unix. When
1990  * file pathname separators need to be inserted, the one that last
1991  * previously occurred in the parameters (reading from left to right)
1992  * is used.
1993  *
1994  * No attempt is made to force the resulting filename to be an absolute
1995  * path. If the first element is a relative path, the result will
1996  * be a relative path. 
1997  * 
1998  * Return value: a newly-allocated string that must be freed with g_free().
1999  **/
2000 gchar *
2001 g_build_filename (const gchar *first_element, 
2002                   ...)
2003 {
2004   gchar *str;
2005   va_list args;
2006
2007   va_start (args, first_element);
2008 #ifndef G_OS_WIN32
2009   str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
2010 #else
2011   str = g_build_pathname_va (first_element, &args, NULL);
2012 #endif
2013   va_end (args);
2014
2015   return str;
2016 }
2017
2018 /**
2019  * g_file_read_link:
2020  * @filename: the symbolic link
2021  * @error: return location for a #GError
2022  *
2023  * Reads the contents of the symbolic link @filename like the POSIX
2024  * readlink() function.  The returned string is in the encoding used
2025  * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
2026  *
2027  * Returns: A newly-allocated string with the contents of the symbolic link, 
2028  *          or %NULL if an error occurred.
2029  *
2030  * Since: 2.4
2031  */
2032 gchar *
2033 g_file_read_link (const gchar  *filename,
2034                   GError      **error)
2035 {
2036 #ifdef HAVE_READLINK
2037   gchar *buffer;
2038   guint size;
2039   gint read_size;    
2040   
2041   size = 256; 
2042   buffer = g_malloc (size);
2043   
2044   while (TRUE) 
2045     {
2046       read_size = readlink (filename, buffer, size);
2047       if (read_size < 0) {
2048         int save_errno = errno;
2049         gchar *display_filename = g_filename_display_name (filename);
2050
2051         g_free (buffer);
2052         g_set_error (error,
2053                      G_FILE_ERROR,
2054                      g_file_error_from_errno (save_errno),
2055                      _("Failed to read the symbolic link '%s': %s"),
2056                      display_filename, 
2057                      g_strerror (save_errno));
2058         g_free (display_filename);
2059         
2060         return NULL;
2061       }
2062     
2063       if (read_size < size) 
2064         {
2065           buffer[read_size] = 0;
2066           return buffer;
2067         }
2068       
2069       size *= 2;
2070       buffer = g_realloc (buffer, size);
2071     }
2072 #else
2073   g_set_error_literal (error,
2074                        G_FILE_ERROR,
2075                        G_FILE_ERROR_INVAL,
2076                        _("Symbolic links not supported"));
2077         
2078   return NULL;
2079 #endif
2080 }
2081
2082 /**
2083  * g_path_is_absolute:
2084  * @file_name: a file name
2085  *
2086  * Returns %TRUE if the given @file_name is an absolute file name.
2087  * Note that this is a somewhat vague concept on Windows.
2088  *
2089  * On POSIX systems, an absolute file name is well-defined. It always
2090  * starts from the single root directory. For example "/usr/local".
2091  *
2092  * On Windows, the concepts of current drive and drive-specific
2093  * current directory introduce vagueness. This function interprets as
2094  * an absolute file name one that either begins with a directory
2095  * separator such as "\Users\tml" or begins with the root on a drive,
2096  * for example "C:\Windows". The first case also includes UNC paths
2097  * such as "\\myserver\docs\foo". In all cases, either slashes or
2098  * backslashes are accepted.
2099  *
2100  * Note that a file name relative to the current drive root does not
2101  * truly specify a file uniquely over time and across processes, as
2102  * the current drive is a per-process value and can be changed.
2103  *
2104  * File names relative the current directory on some specific drive,
2105  * such as "D:foo/bar", are not interpreted as absolute by this
2106  * function, but they obviously are not relative to the normal current
2107  * directory as returned by getcwd() or g_get_current_dir()
2108  * either. Such paths should be avoided, or need to be handled using
2109  * Windows-specific code.
2110  *
2111  * Returns: %TRUE if @file_name is absolute
2112  */
2113 gboolean
2114 g_path_is_absolute (const gchar *file_name)
2115 {
2116   g_return_val_if_fail (file_name != NULL, FALSE);
2117
2118   if (G_IS_DIR_SEPARATOR (file_name[0]))
2119     return TRUE;
2120
2121 #ifdef G_OS_WIN32
2122   /* Recognize drive letter on native Windows */
2123   if (g_ascii_isalpha (file_name[0]) &&
2124       file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
2125     return TRUE;
2126 #endif
2127
2128   return FALSE;
2129 }
2130
2131 /**
2132  * g_path_skip_root:
2133  * @file_name: a file name
2134  *
2135  * Returns a pointer into @file_name after the root component,
2136  * i.e. after the "/" in UNIX or "C:\" under Windows. If @file_name
2137  * is not an absolute path it returns %NULL.
2138  *
2139  * Returns: a pointer into @file_name after the root component
2140  */
2141 const gchar *
2142 g_path_skip_root (const gchar *file_name)
2143 {
2144   g_return_val_if_fail (file_name != NULL, NULL);
2145
2146 #ifdef G_PLATFORM_WIN32
2147   /* Skip \\server\share or //server/share */
2148   if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2149       G_IS_DIR_SEPARATOR (file_name[1]) &&
2150       file_name[2] &&
2151       !G_IS_DIR_SEPARATOR (file_name[2]))
2152     {
2153       gchar *p;
2154       p = strchr (file_name + 2, G_DIR_SEPARATOR);
2155
2156 #ifdef G_OS_WIN32
2157       {
2158         gchar *q;
2159
2160         q = strchr (file_name + 2, '/');
2161         if (p == NULL || (q != NULL && q < p))
2162         p = q;
2163       }
2164 #endif
2165
2166       if (p && p > file_name + 2 && p[1])
2167         {
2168           file_name = p + 1;
2169
2170           while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
2171             file_name++;
2172
2173           /* Possibly skip a backslash after the share name */
2174           if (G_IS_DIR_SEPARATOR (file_name[0]))
2175             file_name++;
2176
2177           return (gchar *)file_name;
2178         }
2179     }
2180 #endif
2181
2182   /* Skip initial slashes */
2183   if (G_IS_DIR_SEPARATOR (file_name[0]))
2184     {
2185       while (G_IS_DIR_SEPARATOR (file_name[0]))
2186         file_name++;
2187       return (gchar *)file_name;
2188     }
2189
2190 #ifdef G_OS_WIN32
2191   /* Skip X:\ */
2192   if (g_ascii_isalpha (file_name[0]) &&
2193       file_name[1] == ':' &&
2194       G_IS_DIR_SEPARATOR (file_name[2]))
2195     return (gchar *)file_name + 3;
2196 #endif
2197
2198   return NULL;
2199 }
2200
2201 /**
2202  * g_basename:
2203  * @file_name: the name of the file
2204  *
2205  * Gets the name of the file without any leading directory
2206  * components. It returns a pointer into the given file name
2207  * string.
2208  *
2209  * Return value: the name of the file without any leading
2210  *     directory components
2211  *
2212  * Deprecated:2.2: Use g_path_get_basename() instead, but notice
2213  *     that g_path_get_basename() allocates new memory for the
2214  *     returned string, unlike this function which returns a pointer
2215  *     into the argument.
2216  */
2217 const gchar *
2218 g_basename (const gchar *file_name)
2219 {
2220   gchar *base;
2221
2222   g_return_val_if_fail (file_name != NULL, NULL);
2223
2224   base = strrchr (file_name, G_DIR_SEPARATOR);
2225
2226 #ifdef G_OS_WIN32
2227   {
2228     gchar *q;
2229     q = strrchr (file_name, '/');
2230     if (base == NULL || (q != NULL && q > base))
2231       base = q;
2232   }
2233 #endif
2234
2235   if (base)
2236     return base + 1;
2237
2238 #ifdef G_OS_WIN32
2239   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2240     return (gchar*) file_name + 2;
2241 #endif
2242
2243   return (gchar*) file_name;
2244 }
2245
2246 /**
2247  * g_path_get_basename:
2248  * @file_name: the name of the file
2249  *
2250  * Gets the last component of the filename.
2251  *
2252  * If @file_name ends with a directory separator it gets the component
2253  * before the last slash. If @file_name consists only of directory
2254  * separators (and on Windows, possibly a drive letter), a single
2255  * separator is returned. If @file_name is empty, it gets ".".
2256  *
2257  * Return value: a newly allocated string containing the last
2258  *    component of the filename
2259  */
2260 gchar *
2261 g_path_get_basename (const gchar *file_name)
2262 {
2263   gssize base;
2264   gssize last_nonslash;
2265   gsize len;
2266   gchar *retval;
2267
2268   g_return_val_if_fail (file_name != NULL, NULL);
2269
2270   if (file_name[0] == '\0')
2271     return g_strdup (".");
2272
2273   last_nonslash = strlen (file_name) - 1;
2274
2275   while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
2276     last_nonslash--;
2277
2278   if (last_nonslash == -1)
2279     /* string only containing slashes */
2280     return g_strdup (G_DIR_SEPARATOR_S);
2281
2282 #ifdef G_OS_WIN32
2283   if (last_nonslash == 1 &&
2284       g_ascii_isalpha (file_name[0]) &&
2285       file_name[1] == ':')
2286     /* string only containing slashes and a drive */
2287     return g_strdup (G_DIR_SEPARATOR_S);
2288 #endif
2289   base = last_nonslash;
2290
2291   while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
2292     base--;
2293
2294 #ifdef G_OS_WIN32
2295   if (base == -1 &&
2296       g_ascii_isalpha (file_name[0]) &&
2297       file_name[1] == ':')
2298     base = 1;
2299 #endif /* G_OS_WIN32 */
2300
2301   len = last_nonslash - base;
2302   retval = g_malloc (len + 1);
2303   memcpy (retval, file_name + base + 1, len);
2304   retval [len] = '\0';
2305
2306   return retval;
2307 }
2308
2309 /**
2310  * g_dirname:
2311  * @file_name: the name of the file
2312  *
2313  * Gets the directory components of a file name.
2314  *
2315  * If the file name has no directory components "." is returned.
2316  * The returned string should be freed when no longer needed.
2317  *
2318  * Returns: the directory components of the file
2319  *
2320  * Deprecated: use g_path_get_dirname() instead
2321  */
2322
2323 /**
2324  * g_path_get_dirname:
2325  * @file_name: the name of the file
2326  *
2327  * Gets the directory components of a file name.
2328  *
2329  * If the file name has no directory components "." is returned.
2330  * The returned string should be freed when no longer needed.
2331  *
2332  * Returns: the directory components of the file
2333  */
2334 gchar *
2335 g_path_get_dirname (const gchar *file_name)
2336 {
2337   gchar *base;
2338   gsize len;
2339
2340   g_return_val_if_fail (file_name != NULL, NULL);
2341
2342   base = strrchr (file_name, G_DIR_SEPARATOR);
2343
2344 #ifdef G_OS_WIN32
2345   {
2346     gchar *q;
2347     q = strrchr (file_name, '/');
2348     if (base == NULL || (q != NULL && q > base))
2349       base = q;
2350   }
2351 #endif
2352
2353   if (!base)
2354     {
2355 #ifdef G_OS_WIN32
2356       if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2357         {
2358           gchar drive_colon_dot[4];
2359
2360           drive_colon_dot[0] = file_name[0];
2361           drive_colon_dot[1] = ':';
2362           drive_colon_dot[2] = '.';
2363           drive_colon_dot[3] = '\0';
2364
2365           return g_strdup (drive_colon_dot);
2366         }
2367 #endif
2368     return g_strdup (".");
2369     }
2370
2371   while (base > file_name && G_IS_DIR_SEPARATOR (*base))
2372     base--;
2373
2374 #ifdef G_OS_WIN32
2375   /* base points to the char before the last slash.
2376    *
2377    * In case file_name is the root of a drive (X:\) or a child of the
2378    * root of a drive (X:\foo), include the slash.
2379    *
2380    * In case file_name is the root share of an UNC path
2381    * (\\server\share), add a slash, returning \\server\share\ .
2382    *
2383    * In case file_name is a direct child of a share in an UNC path
2384    * (\\server\share\foo), include the slash after the share name,
2385    * returning \\server\share\ .
2386    */
2387   if (base == file_name + 1 &&
2388       g_ascii_isalpha (file_name[0]) &&
2389       file_name[1] == ':')
2390     base++;
2391   else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2392            G_IS_DIR_SEPARATOR (file_name[1]) &&
2393            file_name[2] &&
2394            !G_IS_DIR_SEPARATOR (file_name[2]) &&
2395            base >= file_name + 2)
2396     {
2397       const gchar *p = file_name + 2;
2398       while (*p && !G_IS_DIR_SEPARATOR (*p))
2399         p++;
2400       if (p == base + 1)
2401         {
2402           len = (guint) strlen (file_name) + 1;
2403           base = g_new (gchar, len + 1);
2404           strcpy (base, file_name);
2405           base[len-1] = G_DIR_SEPARATOR;
2406           base[len] = 0;
2407           return base;
2408         }
2409       if (G_IS_DIR_SEPARATOR (*p))
2410         {
2411           p++;
2412           while (*p && !G_IS_DIR_SEPARATOR (*p))
2413             p++;
2414           if (p == base + 1)
2415             base++;
2416         }
2417     }
2418 #endif
2419
2420   len = (guint) 1 + base - file_name;
2421   base = g_new (gchar, len + 1);
2422   g_memmove (base, file_name, len);
2423   base[len] = 0;
2424
2425   return base;
2426 }
2427
2428 #if defined(MAXPATHLEN)
2429 #define G_PATH_LENGTH MAXPATHLEN
2430 #elif defined(PATH_MAX)
2431 #define G_PATH_LENGTH PATH_MAX
2432 #elif defined(_PC_PATH_MAX)
2433 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
2434 #else
2435 #define G_PATH_LENGTH 2048
2436 #endif
2437
2438 /**
2439  * g_get_current_dir:
2440  *
2441  * Gets the current directory.
2442  *
2443  * The returned string should be freed when no longer needed.
2444  * The encoding of the returned string is system defined.
2445  * On Windows, it is always UTF-8.
2446  *
2447  * Returns: the current directory
2448  */
2449 gchar *
2450 g_get_current_dir (void)
2451 {
2452 #ifdef G_OS_WIN32
2453
2454   gchar *dir = NULL;
2455   wchar_t dummy[2], *wdir;
2456   int len;
2457
2458   len = GetCurrentDirectoryW (2, dummy);
2459   wdir = g_new (wchar_t, len);
2460
2461   if (GetCurrentDirectoryW (len, wdir) == len - 1)
2462     dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
2463
2464   g_free (wdir);
2465
2466   if (dir == NULL)
2467     dir = g_strdup ("\\");
2468
2469   return dir;
2470
2471 #else
2472
2473   gchar *buffer = NULL;
2474   gchar *dir = NULL;
2475   static gulong max_len = 0;
2476
2477   if (max_len == 0)
2478     max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
2479
2480 #if !defined(HAVE_GETCWD)
2481   buffer = g_new (gchar, max_len + 1);
2482   *buffer = 0;
2483   dir = getwd (buffer);
2484 #else
2485   while (max_len < G_MAXULONG / 2)
2486     {
2487       g_free (buffer);
2488       buffer = g_new (gchar, max_len + 1);
2489       *buffer = 0;
2490       dir = getcwd (buffer, max_len);
2491
2492       if (dir || errno != ERANGE)
2493         break;
2494
2495       max_len *= 2;
2496     }
2497 #endif  /* !sun || !HAVE_GETCWD */
2498
2499   if (!dir || !*buffer)
2500     {
2501       /* hm, should we g_error() out here?
2502        * this can happen if e.g. "./" has mode \0000
2503        */
2504       buffer[0] = G_DIR_SEPARATOR;
2505       buffer[1] = 0;
2506     }
2507
2508   dir = g_strdup (buffer);
2509   g_free (buffer);
2510
2511   return dir;
2512
2513 #endif /* !G_OS_WIN32 */
2514 }
2515
2516
2517 /* NOTE : Keep this part last to ensure nothing in this file uses thn
2518  * below binary compatibility versions.
2519  */
2520 #if defined (G_OS_WIN32) && !defined (_WIN64)
2521
2522 /* Binary compatibility versions. Will be called by code compiled
2523  * against quite old (pre-2.8, I think) headers only, not from more
2524  * recently compiled code.
2525  */
2526
2527 #undef g_file_test
2528
2529 gboolean
2530 g_file_test (const gchar *filename,
2531              GFileTest    test)
2532 {
2533   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
2534   gboolean retval;
2535
2536   if (utf8_filename == NULL)
2537     return FALSE;
2538
2539   retval = g_file_test_utf8 (utf8_filename, test);
2540
2541   g_free (utf8_filename);
2542
2543   return retval;
2544 }
2545
2546 #undef g_file_get_contents
2547
2548 gboolean
2549 g_file_get_contents (const gchar  *filename,
2550                      gchar       **contents,
2551                      gsize        *length,
2552                      GError      **error)
2553 {
2554   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
2555   gboolean retval;
2556
2557   if (utf8_filename == NULL)
2558     return FALSE;
2559
2560   retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
2561
2562   g_free (utf8_filename);
2563
2564   return retval;
2565 }
2566
2567 #undef g_mkstemp
2568
2569 static gint
2570 wrap_libc_open (const gchar *filename,
2571                 int          flags,
2572                 int          mode)
2573 {
2574   return open (filename, flags, mode);
2575 }
2576
2577 gint
2578 g_mkstemp (gchar *tmpl)
2579 {
2580   /* This is the backward compatibility system codepage version,
2581    * thus use normal open().
2582    */
2583   return get_tmp_file (tmpl, wrap_libc_open,
2584                        O_RDWR | O_CREAT | O_EXCL, 0600);
2585 }
2586
2587 #undef g_file_open_tmp
2588
2589 gint
2590 g_file_open_tmp (const gchar  *tmpl,
2591                  gchar       **name_used,
2592                  GError      **error)
2593 {
2594   gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
2595   gchar *utf8_name_used;
2596   gint retval;
2597
2598   if (utf8_tmpl == NULL)
2599     return -1;
2600
2601   retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
2602   
2603   if (retval == -1)
2604     return -1;
2605
2606   if (name_used)
2607     *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
2608
2609   g_free (utf8_name_used);
2610
2611   return retval;
2612 }
2613
2614 #undef g_get_current_dir
2615
2616 gchar *
2617 g_get_current_dir (void)
2618 {
2619   gchar *utf8_dir = g_get_current_dir_utf8 ();
2620   gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
2621   g_free (utf8_dir);
2622   return dir;
2623 }
2624
2625 #endif
2626