gfileutils: Remove extra fclose()
[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 GQuark
463 g_file_error_quark (void)
464 {
465   return g_quark_from_static_string ("g-file-error-quark");
466 }
467
468 /**
469  * g_file_error_from_errno:
470  * @err_no: an "errno" value
471  * 
472  * Gets a #GFileError constant based on the passed-in @err_no.
473  * For example, if you pass in <literal>EEXIST</literal> this function returns
474  * #G_FILE_ERROR_EXIST. Unlike <literal>errno</literal> values, you can portably
475  * assume that all #GFileError values will exist.
476  *
477  * Normally a #GFileError value goes into a #GError returned
478  * from a function that manipulates files. So you would use
479  * g_file_error_from_errno() when constructing a #GError.
480  * 
481  * Return value: #GFileError corresponding to the given @errno
482  **/
483 GFileError
484 g_file_error_from_errno (gint err_no)
485 {
486   switch (err_no)
487     {
488 #ifdef EEXIST
489     case EEXIST:
490       return G_FILE_ERROR_EXIST;
491       break;
492 #endif
493
494 #ifdef EISDIR
495     case EISDIR:
496       return G_FILE_ERROR_ISDIR;
497       break;
498 #endif
499
500 #ifdef EACCES
501     case EACCES:
502       return G_FILE_ERROR_ACCES;
503       break;
504 #endif
505
506 #ifdef ENAMETOOLONG
507     case ENAMETOOLONG:
508       return G_FILE_ERROR_NAMETOOLONG;
509       break;
510 #endif
511
512 #ifdef ENOENT
513     case ENOENT:
514       return G_FILE_ERROR_NOENT;
515       break;
516 #endif
517
518 #ifdef ENOTDIR
519     case ENOTDIR:
520       return G_FILE_ERROR_NOTDIR;
521       break;
522 #endif
523
524 #ifdef ENXIO
525     case ENXIO:
526       return G_FILE_ERROR_NXIO;
527       break;
528 #endif
529
530 #ifdef ENODEV
531     case ENODEV:
532       return G_FILE_ERROR_NODEV;
533       break;
534 #endif
535
536 #ifdef EROFS
537     case EROFS:
538       return G_FILE_ERROR_ROFS;
539       break;
540 #endif
541
542 #ifdef ETXTBSY
543     case ETXTBSY:
544       return G_FILE_ERROR_TXTBSY;
545       break;
546 #endif
547
548 #ifdef EFAULT
549     case EFAULT:
550       return G_FILE_ERROR_FAULT;
551       break;
552 #endif
553
554 #ifdef ELOOP
555     case ELOOP:
556       return G_FILE_ERROR_LOOP;
557       break;
558 #endif
559
560 #ifdef ENOSPC
561     case ENOSPC:
562       return G_FILE_ERROR_NOSPC;
563       break;
564 #endif
565
566 #ifdef ENOMEM
567     case ENOMEM:
568       return G_FILE_ERROR_NOMEM;
569       break;
570 #endif
571
572 #ifdef EMFILE
573     case EMFILE:
574       return G_FILE_ERROR_MFILE;
575       break;
576 #endif
577
578 #ifdef ENFILE
579     case ENFILE:
580       return G_FILE_ERROR_NFILE;
581       break;
582 #endif
583
584 #ifdef EBADF
585     case EBADF:
586       return G_FILE_ERROR_BADF;
587       break;
588 #endif
589
590 #ifdef EINVAL
591     case EINVAL:
592       return G_FILE_ERROR_INVAL;
593       break;
594 #endif
595
596 #ifdef EPIPE
597     case EPIPE:
598       return G_FILE_ERROR_PIPE;
599       break;
600 #endif
601
602 #ifdef EAGAIN
603     case EAGAIN:
604       return G_FILE_ERROR_AGAIN;
605       break;
606 #endif
607
608 #ifdef EINTR
609     case EINTR:
610       return G_FILE_ERROR_INTR;
611       break;
612 #endif
613
614 #ifdef EIO
615     case EIO:
616       return G_FILE_ERROR_IO;
617       break;
618 #endif
619
620 #ifdef EPERM
621     case EPERM:
622       return G_FILE_ERROR_PERM;
623       break;
624 #endif
625
626 #ifdef ENOSYS
627     case ENOSYS:
628       return G_FILE_ERROR_NOSYS;
629       break;
630 #endif
631
632     default:
633       return G_FILE_ERROR_FAILED;
634       break;
635     }
636 }
637
638 static gboolean
639 get_contents_stdio (const gchar  *display_filename,
640                     FILE         *f,
641                     gchar       **contents,
642                     gsize        *length,
643                     GError      **error)
644 {
645   gchar buf[4096];
646   gsize bytes;
647   gchar *str = NULL;
648   gsize total_bytes = 0;
649   gsize total_allocated = 0;
650   gchar *tmp;
651
652   g_assert (f != NULL);
653
654   while (!feof (f))
655     {
656       gint save_errno;
657
658       bytes = fread (buf, 1, sizeof (buf), f);
659       save_errno = errno;
660
661       while ((total_bytes + bytes + 1) > total_allocated)
662         {
663           if (str)
664             total_allocated *= 2;
665           else
666             total_allocated = MIN (bytes + 1, sizeof (buf));
667
668           tmp = g_try_realloc (str, total_allocated);
669
670           if (tmp == NULL)
671             {
672               g_set_error (error,
673                            G_FILE_ERROR,
674                            G_FILE_ERROR_NOMEM,
675                            _("Could not allocate %lu bytes to read file \"%s\""),
676                            (gulong) total_allocated,
677                            display_filename);
678
679               goto error;
680             }
681
682           str = tmp;
683         }
684
685       if (ferror (f))
686         {
687           g_set_error (error,
688                        G_FILE_ERROR,
689                        g_file_error_from_errno (save_errno),
690                        _("Error reading file '%s': %s"),
691                        display_filename,
692                        g_strerror (save_errno));
693
694           goto error;
695         }
696
697       memcpy (str + total_bytes, buf, bytes);
698
699       if (total_bytes + bytes < total_bytes) 
700         {
701           g_set_error (error,
702                        G_FILE_ERROR,
703                        G_FILE_ERROR_FAILED,
704                        _("File \"%s\" is too large"),
705                        display_filename);
706
707           goto error;
708         }
709
710       total_bytes += bytes;
711     }
712
713   fclose (f);
714
715   if (total_allocated == 0)
716     {
717       str = g_new (gchar, 1);
718       total_bytes = 0;
719     }
720
721   str[total_bytes] = '\0';
722
723   if (length)
724     *length = total_bytes;
725
726   *contents = str;
727
728   return TRUE;
729
730  error:
731
732   g_free (str);
733   fclose (f);
734
735   return FALSE;
736 }
737
738 #ifndef G_OS_WIN32
739
740 static gboolean
741 get_contents_regfile (const gchar  *display_filename,
742                       struct stat  *stat_buf,
743                       gint          fd,
744                       gchar       **contents,
745                       gsize        *length,
746                       GError      **error)
747 {
748   gchar *buf;
749   gsize bytes_read;
750   gsize size;
751   gsize alloc_size;
752   
753   size = stat_buf->st_size;
754
755   alloc_size = size + 1;
756   buf = g_try_malloc (alloc_size);
757
758   if (buf == NULL)
759     {
760       g_set_error (error,
761                    G_FILE_ERROR,
762                    G_FILE_ERROR_NOMEM,
763                    _("Could not allocate %lu bytes to read file \"%s\""),
764                    (gulong) alloc_size, 
765                    display_filename);
766
767       goto error;
768     }
769   
770   bytes_read = 0;
771   while (bytes_read < size)
772     {
773       gssize rc;
774           
775       rc = read (fd, buf + bytes_read, size - bytes_read);
776
777       if (rc < 0)
778         {
779           if (errno != EINTR) 
780             {
781               int save_errno = errno;
782
783               g_free (buf);
784               g_set_error (error,
785                            G_FILE_ERROR,
786                            g_file_error_from_errno (save_errno),
787                            _("Failed to read from file '%s': %s"),
788                            display_filename, 
789                            g_strerror (save_errno));
790
791               goto error;
792             }
793         }
794       else if (rc == 0)
795         break;
796       else
797         bytes_read += rc;
798     }
799       
800   buf[bytes_read] = '\0';
801
802   if (length)
803     *length = bytes_read;
804   
805   *contents = buf;
806
807   close (fd);
808
809   return TRUE;
810
811  error:
812
813   close (fd);
814   
815   return FALSE;
816 }
817
818 static gboolean
819 get_contents_posix (const gchar  *filename,
820                     gchar       **contents,
821                     gsize        *length,
822                     GError      **error)
823 {
824   struct stat stat_buf;
825   gint fd;
826   gchar *display_filename = g_filename_display_name (filename);
827
828   /* O_BINARY useful on Cygwin */
829   fd = open (filename, O_RDONLY|O_BINARY);
830
831   if (fd < 0)
832     {
833       int save_errno = errno;
834
835       g_set_error (error,
836                    G_FILE_ERROR,
837                    g_file_error_from_errno (save_errno),
838                    _("Failed to open file '%s': %s"),
839                    display_filename, 
840                    g_strerror (save_errno));
841       g_free (display_filename);
842
843       return FALSE;
844     }
845
846   /* I don't think this will ever fail, aside from ENOMEM, but. */
847   if (fstat (fd, &stat_buf) < 0)
848     {
849       int save_errno = errno;
850
851       close (fd);
852       g_set_error (error,
853                    G_FILE_ERROR,
854                    g_file_error_from_errno (save_errno),
855                    _("Failed to get attributes of file '%s': fstat() failed: %s"),
856                    display_filename, 
857                    g_strerror (save_errno));
858       g_free (display_filename);
859
860       return FALSE;
861     }
862
863   if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
864     {
865       gboolean retval = get_contents_regfile (display_filename,
866                                               &stat_buf,
867                                               fd,
868                                               contents,
869                                               length,
870                                               error);
871       g_free (display_filename);
872
873       return retval;
874     }
875   else
876     {
877       FILE *f;
878       gboolean retval;
879
880       f = fdopen (fd, "r");
881       
882       if (f == NULL)
883         {
884           int save_errno = errno;
885
886           g_set_error (error,
887                        G_FILE_ERROR,
888                        g_file_error_from_errno (save_errno),
889                        _("Failed to open file '%s': fdopen() failed: %s"),
890                        display_filename, 
891                        g_strerror (save_errno));
892           g_free (display_filename);
893
894           return FALSE;
895         }
896   
897       retval = get_contents_stdio (display_filename, f, contents, length, error);
898       g_free (display_filename);
899
900       return retval;
901     }
902 }
903
904 #else  /* G_OS_WIN32 */
905
906 static gboolean
907 get_contents_win32 (const gchar  *filename,
908                     gchar       **contents,
909                     gsize        *length,
910                     GError      **error)
911 {
912   FILE *f;
913   gboolean retval;
914   gchar *display_filename = g_filename_display_name (filename);
915   int save_errno;
916   
917   f = g_fopen (filename, "rb");
918   save_errno = errno;
919
920   if (f == NULL)
921     {
922       g_set_error (error,
923                    G_FILE_ERROR,
924                    g_file_error_from_errno (save_errno),
925                    _("Failed to open file '%s': %s"),
926                    display_filename,
927                    g_strerror (save_errno));
928       g_free (display_filename);
929
930       return FALSE;
931     }
932   
933   retval = get_contents_stdio (display_filename, f, contents, length, error);
934   g_free (display_filename);
935
936   return retval;
937 }
938
939 #endif
940
941 /**
942  * g_file_get_contents:
943  * @filename: (type filename): name of a file to read contents from, in the GLib file name encoding
944  * @contents: (out) (array length=length) (element-type guint8): location to store an allocated string, use g_free() to free
945  *     the returned string
946  * @length: (allow-none): location to store length in bytes of the contents, or %NULL
947  * @error: return location for a #GError, or %NULL
948  *
949  * Reads an entire file into allocated memory, with good error
950  * checking.
951  *
952  * If the call was successful, it returns %TRUE and sets @contents to the file
953  * contents and @length to the length of the file contents in bytes. The string
954  * stored in @contents will be nul-terminated, so for text files you can pass
955  * %NULL for the @length argument. If the call was not successful, it returns
956  * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
957  * codes are those in the #GFileError enumeration. In the error case,
958  * @contents is set to %NULL and @length is set to zero.
959  *
960  * Return value: %TRUE on success, %FALSE if an error occurred
961  **/
962 gboolean
963 g_file_get_contents (const gchar  *filename,
964                      gchar       **contents,
965                      gsize        *length,
966                      GError      **error)
967 {  
968   g_return_val_if_fail (filename != NULL, FALSE);
969   g_return_val_if_fail (contents != NULL, FALSE);
970
971   *contents = NULL;
972   if (length)
973     *length = 0;
974
975 #ifdef G_OS_WIN32
976   return get_contents_win32 (filename, contents, length, error);
977 #else
978   return get_contents_posix (filename, contents, length, error);
979 #endif
980 }
981
982 static gboolean
983 rename_file (const char  *old_name,
984              const char  *new_name,
985              GError     **err)
986 {
987   errno = 0;
988   if (g_rename (old_name, new_name) == -1)
989     {
990       int save_errno = errno;
991       gchar *display_old_name = g_filename_display_name (old_name);
992       gchar *display_new_name = g_filename_display_name (new_name);
993
994       g_set_error (err,
995                    G_FILE_ERROR,
996                    g_file_error_from_errno (save_errno),
997                    _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
998                    display_old_name,
999                    display_new_name,
1000                    g_strerror (save_errno));
1001
1002       g_free (display_old_name);
1003       g_free (display_new_name);
1004       
1005       return FALSE;
1006     }
1007   
1008   return TRUE;
1009 }
1010
1011 static gchar *
1012 write_to_temp_file (const gchar  *contents,
1013                     gssize        length,
1014                     const gchar  *dest_file,
1015                     GError      **err)
1016 {
1017   gchar *tmp_name;
1018   gchar *display_name;
1019   gchar *retval;
1020   FILE *file;
1021   gint fd;
1022   int save_errno;
1023
1024   retval = NULL;
1025   
1026   tmp_name = g_strdup_printf ("%s.XXXXXX", dest_file);
1027
1028   errno = 0;
1029   fd = g_mkstemp_full (tmp_name, O_RDWR | O_BINARY, 0666);
1030   save_errno = errno;
1031
1032   display_name = g_filename_display_name (tmp_name);
1033       
1034   if (fd == -1)
1035     {
1036       g_set_error (err,
1037                    G_FILE_ERROR,
1038                    g_file_error_from_errno (save_errno),
1039                    _("Failed to create file '%s': %s"),
1040                    display_name, g_strerror (save_errno));
1041       
1042       goto out;
1043     }
1044
1045   errno = 0;
1046   file = fdopen (fd, "wb");
1047   if (!file)
1048     {
1049       save_errno = errno;
1050       g_set_error (err,
1051                    G_FILE_ERROR,
1052                    g_file_error_from_errno (save_errno),
1053                    _("Failed to open file '%s' for writing: fdopen() failed: %s"),
1054                    display_name,
1055                    g_strerror (save_errno));
1056
1057       close (fd);
1058       g_unlink (tmp_name);
1059       
1060       goto out;
1061     }
1062
1063   if (length > 0)
1064     {
1065       gsize n_written;
1066       
1067       errno = 0;
1068
1069       n_written = fwrite (contents, 1, length, file);
1070
1071       if (n_written < length)
1072         {
1073           save_errno = errno;
1074       
1075           g_set_error (err,
1076                        G_FILE_ERROR,
1077                        g_file_error_from_errno (save_errno),
1078                        _("Failed to write file '%s': fwrite() failed: %s"),
1079                        display_name,
1080                        g_strerror (save_errno));
1081
1082           fclose (file);
1083           g_unlink (tmp_name);
1084           
1085           goto out;
1086         }
1087     }
1088
1089   errno = 0;
1090   if (fflush (file) != 0)
1091     { 
1092       save_errno = errno;
1093       
1094       g_set_error (err,
1095                    G_FILE_ERROR,
1096                    g_file_error_from_errno (save_errno),
1097                    _("Failed to write file '%s': fflush() failed: %s"),
1098                    display_name, 
1099                    g_strerror (save_errno));
1100
1101       fclose (file);
1102       g_unlink (tmp_name);
1103       
1104       goto out;
1105     }
1106
1107 #ifdef BTRFS_SUPER_MAGIC
1108   {
1109     struct statfs buf;
1110
1111     /* On Linux, on btrfs, skip the fsync since rename-over-existing is
1112      * guaranteed to be atomic and this is the only case in which we
1113      * would fsync() anyway.
1114      */
1115
1116     if (fstatfs (fd, &buf) == 0 && buf.f_type == BTRFS_SUPER_MAGIC)
1117       goto no_fsync;
1118   }
1119 #endif
1120   
1121 #ifdef HAVE_FSYNC
1122   {
1123     struct stat statbuf;
1124
1125     errno = 0;
1126     /* If the final destination exists and is > 0 bytes, we want to sync the
1127      * newly written file to ensure the data is on disk when we rename over
1128      * the destination. Otherwise if we get a system crash we can lose both
1129      * the new and the old file on some filesystems. (I.E. those that don't
1130      * guarantee the data is written to the disk before the metadata.)
1131      */
1132     if (g_lstat (dest_file, &statbuf) == 0 &&
1133         statbuf.st_size > 0 &&
1134         fsync (fileno (file)) != 0)
1135       {
1136         save_errno = errno;
1137
1138         g_set_error (err,
1139                      G_FILE_ERROR,
1140                      g_file_error_from_errno (save_errno),
1141                      _("Failed to write file '%s': fsync() failed: %s"),
1142                      display_name,
1143                      g_strerror (save_errno));
1144
1145         fclose (file);
1146         g_unlink (tmp_name);
1147
1148         goto out;
1149       }
1150   }
1151 #endif
1152
1153 #ifdef BTRFS_SUPER_MAGIC
1154  no_fsync:
1155 #endif
1156   
1157   errno = 0;
1158   if (fclose (file) == EOF)
1159     { 
1160       save_errno = errno;
1161       
1162       g_set_error (err,
1163                    G_FILE_ERROR,
1164                    g_file_error_from_errno (save_errno),
1165                    _("Failed to close file '%s': fclose() failed: %s"),
1166                    display_name, 
1167                    g_strerror (save_errno));
1168
1169       g_unlink (tmp_name);
1170       
1171       goto out;
1172     }
1173
1174   retval = g_strdup (tmp_name);
1175   
1176  out:
1177   g_free (tmp_name);
1178   g_free (display_name);
1179   
1180   return retval;
1181 }
1182
1183 /**
1184  * g_file_set_contents:
1185  * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1186  *   encoding
1187  * @contents: (array length=length) (element-type guint8): string to write to the file
1188  * @length: length of @contents, or -1 if @contents is a nul-terminated string
1189  * @error: return location for a #GError, or %NULL
1190  *
1191  * Writes all of @contents to a file named @filename, with good error checking.
1192  * If a file called @filename already exists it will be overwritten.
1193  *
1194  * This write is atomic in the sense that it is first written to a temporary
1195  * file which is then renamed to the final name. Notes:
1196  * <itemizedlist>
1197  * <listitem>
1198  *    On Unix, if @filename already exists hard links to @filename will break.
1199  *    Also since the file is recreated, existing permissions, access control
1200  *    lists, metadata etc. may be lost. If @filename is a symbolic link,
1201  *    the link itself will be replaced, not the linked file.
1202  * </listitem>
1203  * <listitem>
1204  *   On Windows renaming a file will not remove an existing file with the
1205  *   new name, so on Windows there is a race condition between the existing
1206  *   file being removed and the temporary file being renamed.
1207  * </listitem>
1208  * <listitem>
1209  *   On Windows there is no way to remove a file that is open to some
1210  *   process, or mapped into memory. Thus, this function will fail if
1211  *   @filename already exists and is open.
1212  * </listitem>
1213  * </itemizedlist>
1214  *
1215  * If the call was successful, it returns %TRUE. If the call was not successful,
1216  * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1217  * Possible error codes are those in the #GFileError enumeration.
1218  *
1219  * Note that the name for the temporary file is constructed by appending up
1220  * to 7 characters to @filename.
1221  *
1222  * Return value: %TRUE on success, %FALSE if an error occurred
1223  *
1224  * Since: 2.8
1225  **/
1226 gboolean
1227 g_file_set_contents (const gchar  *filename,
1228                      const gchar  *contents,
1229                      gssize        length,
1230                      GError      **error)
1231 {
1232   gchar *tmp_filename;
1233   gboolean retval;
1234   GError *rename_error = NULL;
1235   
1236   g_return_val_if_fail (filename != NULL, FALSE);
1237   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1238   g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1239   g_return_val_if_fail (length >= -1, FALSE);
1240   
1241   if (length == -1)
1242     length = strlen (contents);
1243
1244   tmp_filename = write_to_temp_file (contents, length, filename, error);
1245   
1246   if (!tmp_filename)
1247     {
1248       retval = FALSE;
1249       goto out;
1250     }
1251
1252   if (!rename_file (tmp_filename, filename, &rename_error))
1253     {
1254 #ifndef G_OS_WIN32
1255
1256       g_unlink (tmp_filename);
1257       g_propagate_error (error, rename_error);
1258       retval = FALSE;
1259       goto out;
1260
1261 #else /* G_OS_WIN32 */
1262       
1263       /* Renaming failed, but on Windows this may just mean
1264        * the file already exists. So if the target file
1265        * exists, try deleting it and do the rename again.
1266        */
1267       if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1268         {
1269           g_unlink (tmp_filename);
1270           g_propagate_error (error, rename_error);
1271           retval = FALSE;
1272           goto out;
1273         }
1274
1275       g_error_free (rename_error);
1276       
1277       if (g_unlink (filename) == -1)
1278         {
1279           gchar *display_filename = g_filename_display_name (filename);
1280
1281           int save_errno = errno;
1282           
1283           g_set_error (error,
1284                        G_FILE_ERROR,
1285                        g_file_error_from_errno (save_errno),
1286                        _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1287                        display_filename,
1288                        g_strerror (save_errno));
1289
1290           g_free (display_filename);
1291           g_unlink (tmp_filename);
1292           retval = FALSE;
1293           goto out;
1294         }
1295       
1296       if (!rename_file (tmp_filename, filename, error))
1297         {
1298           g_unlink (tmp_filename);
1299           retval = FALSE;
1300           goto out;
1301         }
1302
1303 #endif
1304     }
1305
1306   retval = TRUE;
1307   
1308  out:
1309   g_free (tmp_filename);
1310   return retval;
1311 }
1312
1313 /*
1314  * get_tmp_file based on the mkstemp implementation from the GNU C library.
1315  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1316  */
1317 typedef gint (*GTmpFileCallback) (gchar *, gint, gint);
1318
1319 static gint
1320 get_tmp_file (gchar            *tmpl,
1321               GTmpFileCallback  f,
1322               int               flags,
1323               int               mode)
1324 {
1325   char *XXXXXX;
1326   int count, fd;
1327   static const char letters[] =
1328     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1329   static const int NLETTERS = sizeof (letters) - 1;
1330   glong value;
1331   GTimeVal tv;
1332   static int counter = 0;
1333
1334   g_return_val_if_fail (tmpl != NULL, -1);
1335
1336   /* find the last occurrence of "XXXXXX" */
1337   XXXXXX = g_strrstr (tmpl, "XXXXXX");
1338
1339   if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1340     {
1341       errno = EINVAL;
1342       return -1;
1343     }
1344
1345   /* Get some more or less random data.  */
1346   g_get_current_time (&tv);
1347   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1348
1349   for (count = 0; count < 100; value += 7777, ++count)
1350     {
1351       glong v = value;
1352
1353       /* Fill in the random bits.  */
1354       XXXXXX[0] = letters[v % NLETTERS];
1355       v /= NLETTERS;
1356       XXXXXX[1] = letters[v % NLETTERS];
1357       v /= NLETTERS;
1358       XXXXXX[2] = letters[v % NLETTERS];
1359       v /= NLETTERS;
1360       XXXXXX[3] = letters[v % NLETTERS];
1361       v /= NLETTERS;
1362       XXXXXX[4] = letters[v % NLETTERS];
1363       v /= NLETTERS;
1364       XXXXXX[5] = letters[v % NLETTERS];
1365
1366       fd = f (tmpl, flags, mode);
1367
1368       if (fd >= 0)
1369         return fd;
1370       else if (errno != EEXIST)
1371         /* Any other error will apply also to other names we might
1372          *  try, and there are 2^32 or so of them, so give up now.
1373          */
1374         return -1;
1375     }
1376
1377   /* We got out of the loop because we ran out of combinations to try.  */
1378   errno = EEXIST;
1379   return -1;
1380 }
1381
1382 static gint
1383 wrap_mkdir (gchar *tmpl,
1384             int    flags G_GNUC_UNUSED,
1385             int    mode)
1386 {
1387   /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1388   return g_mkdir (tmpl, mode);
1389 }
1390
1391 /**
1392  * g_mkdtemp_full:
1393  * @tmpl: (type filename): template directory name
1394  * @mode: permissions to create the temporary directory with
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. The X string will be modified to form
1404  * the name of a directory that didn't exist. The string should be
1405  * in the GLib file name encoding. Most importantly, on Windows it
1406  * 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_full (gchar *tmpl,
1416                 gint   mode)
1417 {
1418   if (get_tmp_file (tmpl, wrap_mkdir, 0, mode) == -1)
1419     return NULL;
1420   else
1421     return tmpl;
1422 }
1423
1424 /**
1425  * g_mkdtemp:
1426  * @tmpl: (type filename): template directory name
1427  *
1428  * Creates a temporary directory. See the mkdtemp() documentation
1429  * on most UNIX-like systems.
1430  *
1431  * The parameter is a string that should follow the rules for
1432  * mkdtemp() templates, i.e. contain the string "XXXXXX".
1433  * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1434  * sequence does not have to occur at the very end of the template
1435  * and you can pass a @mode and additional @flags. The X string will
1436  * be modified to form the name of a directory that didn't exist.
1437  * The string should be in the GLib file name encoding. Most importantly,
1438  * on Windows it should be in UTF-8.
1439  *
1440  * Return value: A pointer to @tmpl, which has been modified
1441  *     to hold the directory name.  In case of errors, %NULL is
1442  *     returned and %errno will be set.
1443  *
1444  * Since: 2.30
1445  */
1446 gchar *
1447 g_mkdtemp (gchar *tmpl)
1448 {
1449   return g_mkdtemp_full (tmpl, 0700);
1450 }
1451
1452 /**
1453  * g_mkstemp_full:
1454  * @tmpl: (type filename): template filename
1455  * @flags: flags to pass to an open() call in addition to O_EXCL
1456  *     and O_CREAT, which are passed automatically
1457  * @mode: permissions to create the temporary file with
1458  *
1459  * Opens a temporary file. See the mkstemp() documentation
1460  * on most UNIX-like systems.
1461  *
1462  * The parameter is a string that should follow the rules for
1463  * mkstemp() templates, i.e. contain the string "XXXXXX".
1464  * g_mkstemp_full() is slightly more flexible than mkstemp()
1465  * in that the sequence does not have to occur at the very end of the
1466  * template and you can pass a @mode and additional @flags. The X
1467  * string will be modified to form the name of a file that didn't exist.
1468  * The string should be in the GLib file name encoding. Most importantly,
1469  * 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 handle should be
1473  *     closed with close(). In case of errors, -1 is returned
1474  *     and %errno will be set.
1475  *
1476  * Since: 2.22
1477  */
1478 gint
1479 g_mkstemp_full (gchar *tmpl,
1480                 gint   flags,
1481                 gint   mode)
1482 {
1483   /* tmpl is in UTF-8 on Windows, thus use g_open() */
1484   return get_tmp_file (tmpl, (GTmpFileCallback) g_open,
1485                        flags | O_CREAT | O_EXCL, mode);
1486 }
1487
1488 /**
1489  * g_mkstemp:
1490  * @tmpl: (type filename): template filename
1491  *
1492  * Opens a temporary file. See the mkstemp() documentation
1493  * on most UNIX-like systems.
1494  *
1495  * The parameter is a string that should follow the rules for
1496  * mkstemp() templates, i.e. contain the string "XXXXXX".
1497  * g_mkstemp() is slightly more flexible than mkstemp() in that the
1498  * sequence does not have to occur at the very end of the template.
1499  * The X string will be modified to form the name of a file that
1500  * didn't exist. The string should be in the GLib file name encoding.
1501  * Most importantly, on Windows it should be in UTF-8.
1502  *
1503  * Return value: A file handle (as from open()) to the file
1504  *     opened for reading and writing. The file is opened in binary
1505  *     mode on platforms where there is a difference. The file handle
1506  *     should be closed with close(). In case of errors, -1 is
1507  *     returned and %errno will be set.
1508  */
1509 gint
1510 g_mkstemp (gchar *tmpl)
1511 {
1512   return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1513 }
1514
1515 static gint
1516 g_get_tmp_name (const gchar      *tmpl,
1517                 gchar           **name_used,
1518                 GTmpFileCallback  f,
1519                 gint              flags,
1520                 gint              mode,
1521                 GError          **error)
1522 {
1523   int retval;
1524   const char *tmpdir;
1525   const char *sep;
1526   char *fulltemplate;
1527   const char *slash;
1528
1529   if (tmpl == NULL)
1530     tmpl = ".XXXXXX";
1531
1532   if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1533 #ifdef G_OS_WIN32
1534       || (strchr (tmpl, '/') != NULL && (slash = "/"))
1535 #endif
1536       )
1537     {
1538       gchar *display_tmpl = g_filename_display_name (tmpl);
1539       char c[2];
1540       c[0] = *slash;
1541       c[1] = '\0';
1542
1543       g_set_error (error,
1544                    G_FILE_ERROR,
1545                    G_FILE_ERROR_FAILED,
1546                    _("Template '%s' invalid, should not contain a '%s'"),
1547                    display_tmpl, c);
1548       g_free (display_tmpl);
1549
1550       return -1;
1551     }
1552
1553   if (strstr (tmpl, "XXXXXX") == NULL)
1554     {
1555       gchar *display_tmpl = g_filename_display_name (tmpl);
1556       g_set_error (error,
1557                    G_FILE_ERROR,
1558                    G_FILE_ERROR_FAILED,
1559                    _("Template '%s' doesn't contain XXXXXX"),
1560                    display_tmpl);
1561       g_free (display_tmpl);
1562       return -1;
1563     }
1564
1565   tmpdir = g_get_tmp_dir ();
1566
1567   if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1568     sep = "";
1569   else
1570     sep = G_DIR_SEPARATOR_S;
1571
1572   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1573
1574   retval = get_tmp_file (fulltemplate, f, flags, mode);
1575   if (retval == -1)
1576     {
1577       int save_errno = errno;
1578       gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1579
1580       g_set_error (error,
1581                    G_FILE_ERROR,
1582                    g_file_error_from_errno (save_errno),
1583                    _("Failed to create file '%s': %s"),
1584                    display_fulltemplate, g_strerror (save_errno));
1585       g_free (display_fulltemplate);
1586       g_free (fulltemplate);
1587       return -1;
1588     }
1589
1590   *name_used = fulltemplate;
1591
1592   return retval;
1593 }
1594
1595 /**
1596  * g_file_open_tmp:
1597  * @tmpl: (type filename) (allow-none): Template for file name, as in
1598  *     g_mkstemp(), basename only, or %NULL for a default template
1599  * @name_used: (out) (type filename): location to store actual name used,
1600  *     or %NULL
1601  * @error: return location for a #GError
1602  *
1603  * Opens a file for writing in the preferred directory for temporary
1604  * files (as returned by g_get_tmp_dir()).
1605  *
1606  * @tmpl should be a string in the GLib file name encoding containing
1607  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1608  * However, unlike these functions, the template should only be a
1609  * basename, no directory components are allowed. If template is
1610  * %NULL, a default template is used.
1611  *
1612  * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
1613  * modified, and might thus be a read-only literal string.
1614  *
1615  * Upon success, and if @name_used is non-%NULL, the actual name used
1616  * is returned in @name_used. This string should be freed with g_free()
1617  * when not needed any longer. The returned name is in the GLib file
1618  * name encoding.
1619  *
1620  * Return value: A file handle (as from open()) to the file opened for
1621  *     reading and writing. The file is opened in binary mode on platforms
1622  *     where there is a difference. The file handle should be closed with
1623  *     close(). In case of errors, -1 is returned and @error will be set.
1624  */
1625 gint
1626 g_file_open_tmp (const gchar  *tmpl,
1627                  gchar       **name_used,
1628                  GError      **error)
1629 {
1630   gchar *fulltemplate;
1631   gint result;
1632
1633   result = g_get_tmp_name (tmpl, &fulltemplate,
1634                            (GTmpFileCallback) g_open,
1635                            O_CREAT | O_EXCL | O_RDWR | O_BINARY,
1636                            0600,
1637                            error);
1638   if (result != -1)
1639     {
1640       if (name_used)
1641         *name_used = fulltemplate;
1642       else
1643         g_free (fulltemplate);
1644     }
1645
1646   return result;
1647 }
1648
1649 /**
1650  * g_dir_make_tmp:
1651  * @tmpl: (type filename) (allow-none): Template for directory name,
1652  *     as in g_mkdtemp(), basename only, or %NULL for a default template
1653  * @error: return location for a #GError
1654  *
1655  * Creates a subdirectory in the preferred directory for temporary
1656  * files (as returned by g_get_tmp_dir()).
1657  *
1658  * @tmpl should be a string in the GLib file name encoding containing
1659  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1660  * However, unlike these functions, the template should only be a
1661  * basename, no directory components are allowed. If template is
1662  * %NULL, a default template is used.
1663  *
1664  * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
1665  * modified, and might thus be a read-only literal string.
1666  *
1667  * Return value: (type filename): The actual name used. This string
1668  *     should be freed with g_free() when not needed any longer and is
1669  *     is in the GLib file name encoding. In case of errors, %NULL is
1670  *     returned and @error will be set.
1671  *
1672  * Since: 2.30
1673  */
1674 gchar *
1675 g_dir_make_tmp (const gchar  *tmpl,
1676                 GError      **error)
1677 {
1678   gchar *fulltemplate;
1679
1680   if (g_get_tmp_name (tmpl, &fulltemplate, wrap_mkdir, 0, 0700, error) == -1)
1681     return NULL;
1682   else
1683     return fulltemplate;
1684 }
1685
1686 static gchar *
1687 g_build_path_va (const gchar  *separator,
1688                  const gchar  *first_element,
1689                  va_list      *args,
1690                  gchar       **str_array)
1691 {
1692   GString *result;
1693   gint separator_len = strlen (separator);
1694   gboolean is_first = TRUE;
1695   gboolean have_leading = FALSE;
1696   const gchar *single_element = NULL;
1697   const gchar *next_element;
1698   const gchar *last_trailing = NULL;
1699   gint i = 0;
1700
1701   result = g_string_new (NULL);
1702
1703   if (str_array)
1704     next_element = str_array[i++];
1705   else
1706     next_element = first_element;
1707
1708   while (TRUE)
1709     {
1710       const gchar *element;
1711       const gchar *start;
1712       const gchar *end;
1713
1714       if (next_element)
1715         {
1716           element = next_element;
1717           if (str_array)
1718             next_element = str_array[i++];
1719           else
1720             next_element = va_arg (*args, gchar *);
1721         }
1722       else
1723         break;
1724
1725       /* Ignore empty elements */
1726       if (!*element)
1727         continue;
1728       
1729       start = element;
1730
1731       if (separator_len)
1732         {
1733           while (strncmp (start, separator, separator_len) == 0)
1734             start += separator_len;
1735         }
1736
1737       end = start + strlen (start);
1738       
1739       if (separator_len)
1740         {
1741           while (end >= start + separator_len &&
1742                  strncmp (end - separator_len, separator, separator_len) == 0)
1743             end -= separator_len;
1744           
1745           last_trailing = end;
1746           while (last_trailing >= element + separator_len &&
1747                  strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1748             last_trailing -= separator_len;
1749
1750           if (!have_leading)
1751             {
1752               /* If the leading and trailing separator strings are in the
1753                * same element and overlap, the result is exactly that element
1754                */
1755               if (last_trailing <= start)
1756                 single_element = element;
1757                   
1758               g_string_append_len (result, element, start - element);
1759               have_leading = TRUE;
1760             }
1761           else
1762             single_element = NULL;
1763         }
1764
1765       if (end == start)
1766         continue;
1767
1768       if (!is_first)
1769         g_string_append (result, separator);
1770       
1771       g_string_append_len (result, start, end - start);
1772       is_first = FALSE;
1773     }
1774
1775   if (single_element)
1776     {
1777       g_string_free (result, TRUE);
1778       return g_strdup (single_element);
1779     }
1780   else
1781     {
1782       if (last_trailing)
1783         g_string_append (result, last_trailing);
1784   
1785       return g_string_free (result, FALSE);
1786     }
1787 }
1788
1789 /**
1790  * g_build_pathv:
1791  * @separator: a string used to separator the elements of the path.
1792  * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
1793  * 
1794  * Behaves exactly like g_build_path(), but takes the path elements 
1795  * as a string array, instead of varargs. This function is mainly
1796  * meant for language bindings.
1797  *
1798  * Return value: a newly-allocated string that must be freed with g_free().
1799  *
1800  * Since: 2.8
1801  */
1802 gchar *
1803 g_build_pathv (const gchar  *separator,
1804                gchar       **args)
1805 {
1806   if (!args)
1807     return NULL;
1808
1809   return g_build_path_va (separator, NULL, NULL, args);
1810 }
1811
1812
1813 /**
1814  * g_build_path:
1815  * @separator: a string used to separator the elements of the path.
1816  * @first_element: the first element in the path
1817  * @...: remaining elements in path, terminated by %NULL
1818  * 
1819  * Creates a path from a series of elements using @separator as the
1820  * separator between elements. At the boundary between two elements,
1821  * any trailing occurrences of separator in the first element, or
1822  * leading occurrences of separator in the second element are removed
1823  * and exactly one copy of the separator is inserted.
1824  *
1825  * Empty elements are ignored.
1826  *
1827  * The number of leading copies of the separator on the result is
1828  * the same as the number of leading copies of the separator on
1829  * the first non-empty element.
1830  *
1831  * The number of trailing copies of the separator on the result is
1832  * the same as the number of trailing copies of the separator on
1833  * the last non-empty element. (Determination of the number of
1834  * trailing copies is done without stripping leading copies, so
1835  * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1836  * has 1 trailing copy.)
1837  *
1838  * However, if there is only a single non-empty element, and there
1839  * are no characters in that element not part of the leading or
1840  * trailing separators, then the result is exactly the original value
1841  * of that element.
1842  *
1843  * Other than for determination of the number of leading and trailing
1844  * copies of the separator, elements consisting only of copies
1845  * of the separator are ignored.
1846  * 
1847  * Return value: a newly-allocated string that must be freed with g_free().
1848  **/
1849 gchar *
1850 g_build_path (const gchar *separator,
1851               const gchar *first_element,
1852               ...)
1853 {
1854   gchar *str;
1855   va_list args;
1856
1857   g_return_val_if_fail (separator != NULL, NULL);
1858
1859   va_start (args, first_element);
1860   str = g_build_path_va (separator, first_element, &args, NULL);
1861   va_end (args);
1862
1863   return str;
1864 }
1865
1866 #ifdef G_OS_WIN32
1867
1868 static gchar *
1869 g_build_pathname_va (const gchar  *first_element,
1870                      va_list      *args,
1871                      gchar       **str_array)
1872 {
1873   /* Code copied from g_build_pathv(), and modified to use two
1874    * alternative single-character separators.
1875    */
1876   GString *result;
1877   gboolean is_first = TRUE;
1878   gboolean have_leading = FALSE;
1879   const gchar *single_element = NULL;
1880   const gchar *next_element;
1881   const gchar *last_trailing = NULL;
1882   gchar current_separator = '\\';
1883   gint i = 0;
1884
1885   result = g_string_new (NULL);
1886
1887   if (str_array)
1888     next_element = str_array[i++];
1889   else
1890     next_element = first_element;
1891   
1892   while (TRUE)
1893     {
1894       const gchar *element;
1895       const gchar *start;
1896       const gchar *end;
1897
1898       if (next_element)
1899         {
1900           element = next_element;
1901           if (str_array)
1902             next_element = str_array[i++];
1903           else
1904             next_element = va_arg (*args, gchar *);
1905         }
1906       else
1907         break;
1908
1909       /* Ignore empty elements */
1910       if (!*element)
1911         continue;
1912       
1913       start = element;
1914
1915       if (TRUE)
1916         {
1917           while (start &&
1918                  (*start == '\\' || *start == '/'))
1919             {
1920               current_separator = *start;
1921               start++;
1922             }
1923         }
1924
1925       end = start + strlen (start);
1926       
1927       if (TRUE)
1928         {
1929           while (end >= start + 1 &&
1930                  (end[-1] == '\\' || end[-1] == '/'))
1931             {
1932               current_separator = end[-1];
1933               end--;
1934             }
1935           
1936           last_trailing = end;
1937           while (last_trailing >= element + 1 &&
1938                  (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1939             last_trailing--;
1940
1941           if (!have_leading)
1942             {
1943               /* If the leading and trailing separator strings are in the
1944                * same element and overlap, the result is exactly that element
1945                */
1946               if (last_trailing <= start)
1947                 single_element = element;
1948                   
1949               g_string_append_len (result, element, start - element);
1950               have_leading = TRUE;
1951             }
1952           else
1953             single_element = NULL;
1954         }
1955
1956       if (end == start)
1957         continue;
1958
1959       if (!is_first)
1960         g_string_append_len (result, &current_separator, 1);
1961       
1962       g_string_append_len (result, start, end - start);
1963       is_first = FALSE;
1964     }
1965
1966   if (single_element)
1967     {
1968       g_string_free (result, TRUE);
1969       return g_strdup (single_element);
1970     }
1971   else
1972     {
1973       if (last_trailing)
1974         g_string_append (result, last_trailing);
1975   
1976       return g_string_free (result, FALSE);
1977     }
1978 }
1979
1980 #endif
1981
1982 /**
1983  * g_build_filenamev:
1984  * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
1985  * 
1986  * Behaves exactly like g_build_filename(), but takes the path elements 
1987  * as a string array, instead of varargs. This function is mainly
1988  * meant for language bindings.
1989  *
1990  * Return value: a newly-allocated string that must be freed with g_free().
1991  * 
1992  * Since: 2.8
1993  */
1994 gchar *
1995 g_build_filenamev (gchar **args)
1996 {
1997   gchar *str;
1998
1999 #ifndef G_OS_WIN32
2000   str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
2001 #else
2002   str = g_build_pathname_va (NULL, NULL, args);
2003 #endif
2004
2005   return str;
2006 }
2007
2008 /**
2009  * g_build_filename:
2010  * @first_element: the first element in the path
2011  * @...: remaining elements in path, terminated by %NULL
2012  * 
2013  * Creates a filename from a series of elements using the correct
2014  * separator for filenames.
2015  *
2016  * On Unix, this function behaves identically to <literal>g_build_path
2017  * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
2018  *
2019  * On Windows, it takes into account that either the backslash
2020  * (<literal>\</literal> or slash (<literal>/</literal>) can be used
2021  * as separator in filenames, but otherwise behaves as on Unix. When
2022  * file pathname separators need to be inserted, the one that last
2023  * previously occurred in the parameters (reading from left to right)
2024  * is used.
2025  *
2026  * No attempt is made to force the resulting filename to be an absolute
2027  * path. If the first element is a relative path, the result will
2028  * be a relative path. 
2029  * 
2030  * Return value: a newly-allocated string that must be freed with g_free().
2031  **/
2032 gchar *
2033 g_build_filename (const gchar *first_element, 
2034                   ...)
2035 {
2036   gchar *str;
2037   va_list args;
2038
2039   va_start (args, first_element);
2040 #ifndef G_OS_WIN32
2041   str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
2042 #else
2043   str = g_build_pathname_va (first_element, &args, NULL);
2044 #endif
2045   va_end (args);
2046
2047   return str;
2048 }
2049
2050 /**
2051  * g_file_read_link:
2052  * @filename: the symbolic link
2053  * @error: return location for a #GError
2054  *
2055  * Reads the contents of the symbolic link @filename like the POSIX
2056  * readlink() function.  The returned string is in the encoding used
2057  * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
2058  *
2059  * Returns: A newly-allocated string with the contents of the symbolic link, 
2060  *          or %NULL if an error occurred.
2061  *
2062  * Since: 2.4
2063  */
2064 gchar *
2065 g_file_read_link (const gchar  *filename,
2066                   GError      **error)
2067 {
2068 #ifdef HAVE_READLINK
2069   gchar *buffer;
2070   guint size;
2071   gint read_size;    
2072   
2073   size = 256; 
2074   buffer = g_malloc (size);
2075   
2076   while (TRUE) 
2077     {
2078       read_size = readlink (filename, buffer, size);
2079       if (read_size < 0) {
2080         int save_errno = errno;
2081         gchar *display_filename = g_filename_display_name (filename);
2082
2083         g_free (buffer);
2084         g_set_error (error,
2085                      G_FILE_ERROR,
2086                      g_file_error_from_errno (save_errno),
2087                      _("Failed to read the symbolic link '%s': %s"),
2088                      display_filename, 
2089                      g_strerror (save_errno));
2090         g_free (display_filename);
2091         
2092         return NULL;
2093       }
2094     
2095       if (read_size < size) 
2096         {
2097           buffer[read_size] = 0;
2098           return buffer;
2099         }
2100       
2101       size *= 2;
2102       buffer = g_realloc (buffer, size);
2103     }
2104 #else
2105   g_set_error_literal (error,
2106                        G_FILE_ERROR,
2107                        G_FILE_ERROR_INVAL,
2108                        _("Symbolic links not supported"));
2109         
2110   return NULL;
2111 #endif
2112 }
2113
2114 /**
2115  * g_path_is_absolute:
2116  * @file_name: a file name
2117  *
2118  * Returns %TRUE if the given @file_name is an absolute file name.
2119  * Note that this is a somewhat vague concept on Windows.
2120  *
2121  * On POSIX systems, an absolute file name is well-defined. It always
2122  * starts from the single root directory. For example "/usr/local".
2123  *
2124  * On Windows, the concepts of current drive and drive-specific
2125  * current directory introduce vagueness. This function interprets as
2126  * an absolute file name one that either begins with a directory
2127  * separator such as "\Users\tml" or begins with the root on a drive,
2128  * for example "C:\Windows". The first case also includes UNC paths
2129  * such as "\\myserver\docs\foo". In all cases, either slashes or
2130  * backslashes are accepted.
2131  *
2132  * Note that a file name relative to the current drive root does not
2133  * truly specify a file uniquely over time and across processes, as
2134  * the current drive is a per-process value and can be changed.
2135  *
2136  * File names relative the current directory on some specific drive,
2137  * such as "D:foo/bar", are not interpreted as absolute by this
2138  * function, but they obviously are not relative to the normal current
2139  * directory as returned by getcwd() or g_get_current_dir()
2140  * either. Such paths should be avoided, or need to be handled using
2141  * Windows-specific code.
2142  *
2143  * Returns: %TRUE if @file_name is absolute
2144  */
2145 gboolean
2146 g_path_is_absolute (const gchar *file_name)
2147 {
2148   g_return_val_if_fail (file_name != NULL, FALSE);
2149
2150   if (G_IS_DIR_SEPARATOR (file_name[0]))
2151     return TRUE;
2152
2153 #ifdef G_OS_WIN32
2154   /* Recognize drive letter on native Windows */
2155   if (g_ascii_isalpha (file_name[0]) &&
2156       file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
2157     return TRUE;
2158 #endif
2159
2160   return FALSE;
2161 }
2162
2163 /**
2164  * g_path_skip_root:
2165  * @file_name: a file name
2166  *
2167  * Returns a pointer into @file_name after the root component,
2168  * i.e. after the "/" in UNIX or "C:\" under Windows. If @file_name
2169  * is not an absolute path it returns %NULL.
2170  *
2171  * Returns: a pointer into @file_name after the root component
2172  */
2173 const gchar *
2174 g_path_skip_root (const gchar *file_name)
2175 {
2176   g_return_val_if_fail (file_name != NULL, NULL);
2177
2178 #ifdef G_PLATFORM_WIN32
2179   /* Skip \\server\share or //server/share */
2180   if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2181       G_IS_DIR_SEPARATOR (file_name[1]) &&
2182       file_name[2] &&
2183       !G_IS_DIR_SEPARATOR (file_name[2]))
2184     {
2185       gchar *p;
2186       p = strchr (file_name + 2, G_DIR_SEPARATOR);
2187
2188 #ifdef G_OS_WIN32
2189       {
2190         gchar *q;
2191
2192         q = strchr (file_name + 2, '/');
2193         if (p == NULL || (q != NULL && q < p))
2194         p = q;
2195       }
2196 #endif
2197
2198       if (p && p > file_name + 2 && p[1])
2199         {
2200           file_name = p + 1;
2201
2202           while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
2203             file_name++;
2204
2205           /* Possibly skip a backslash after the share name */
2206           if (G_IS_DIR_SEPARATOR (file_name[0]))
2207             file_name++;
2208
2209           return (gchar *)file_name;
2210         }
2211     }
2212 #endif
2213
2214   /* Skip initial slashes */
2215   if (G_IS_DIR_SEPARATOR (file_name[0]))
2216     {
2217       while (G_IS_DIR_SEPARATOR (file_name[0]))
2218         file_name++;
2219       return (gchar *)file_name;
2220     }
2221
2222 #ifdef G_OS_WIN32
2223   /* Skip X:\ */
2224   if (g_ascii_isalpha (file_name[0]) &&
2225       file_name[1] == ':' &&
2226       G_IS_DIR_SEPARATOR (file_name[2]))
2227     return (gchar *)file_name + 3;
2228 #endif
2229
2230   return NULL;
2231 }
2232
2233 /**
2234  * g_basename:
2235  * @file_name: the name of the file
2236  *
2237  * Gets the name of the file without any leading directory
2238  * components. It returns a pointer into the given file name
2239  * string.
2240  *
2241  * Return value: the name of the file without any leading
2242  *     directory components
2243  *
2244  * Deprecated:2.2: Use g_path_get_basename() instead, but notice
2245  *     that g_path_get_basename() allocates new memory for the
2246  *     returned string, unlike this function which returns a pointer
2247  *     into the argument.
2248  */
2249 const gchar *
2250 g_basename (const gchar *file_name)
2251 {
2252   gchar *base;
2253
2254   g_return_val_if_fail (file_name != NULL, NULL);
2255
2256   base = strrchr (file_name, G_DIR_SEPARATOR);
2257
2258 #ifdef G_OS_WIN32
2259   {
2260     gchar *q;
2261     q = strrchr (file_name, '/');
2262     if (base == NULL || (q != NULL && q > base))
2263       base = q;
2264   }
2265 #endif
2266
2267   if (base)
2268     return base + 1;
2269
2270 #ifdef G_OS_WIN32
2271   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2272     return (gchar*) file_name + 2;
2273 #endif
2274
2275   return (gchar*) file_name;
2276 }
2277
2278 /**
2279  * g_path_get_basename:
2280  * @file_name: the name of the file
2281  *
2282  * Gets the last component of the filename.
2283  *
2284  * If @file_name ends with a directory separator it gets the component
2285  * before the last slash. If @file_name consists only of directory
2286  * separators (and on Windows, possibly a drive letter), a single
2287  * separator is returned. If @file_name is empty, it gets ".".
2288  *
2289  * Return value: a newly allocated string containing the last
2290  *    component of the filename
2291  */
2292 gchar *
2293 g_path_get_basename (const gchar *file_name)
2294 {
2295   gssize base;
2296   gssize last_nonslash;
2297   gsize len;
2298   gchar *retval;
2299
2300   g_return_val_if_fail (file_name != NULL, NULL);
2301
2302   if (file_name[0] == '\0')
2303     return g_strdup (".");
2304
2305   last_nonslash = strlen (file_name) - 1;
2306
2307   while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
2308     last_nonslash--;
2309
2310   if (last_nonslash == -1)
2311     /* string only containing slashes */
2312     return g_strdup (G_DIR_SEPARATOR_S);
2313
2314 #ifdef G_OS_WIN32
2315   if (last_nonslash == 1 &&
2316       g_ascii_isalpha (file_name[0]) &&
2317       file_name[1] == ':')
2318     /* string only containing slashes and a drive */
2319     return g_strdup (G_DIR_SEPARATOR_S);
2320 #endif
2321   base = last_nonslash;
2322
2323   while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
2324     base--;
2325
2326 #ifdef G_OS_WIN32
2327   if (base == -1 &&
2328       g_ascii_isalpha (file_name[0]) &&
2329       file_name[1] == ':')
2330     base = 1;
2331 #endif /* G_OS_WIN32 */
2332
2333   len = last_nonslash - base;
2334   retval = g_malloc (len + 1);
2335   memcpy (retval, file_name + base + 1, len);
2336   retval [len] = '\0';
2337
2338   return retval;
2339 }
2340
2341 /**
2342  * g_dirname:
2343  * @file_name: the name of the file
2344  *
2345  * Gets the directory components of a file name.
2346  *
2347  * If the file name has no directory components "." is returned.
2348  * The returned string should be freed when no longer needed.
2349  *
2350  * Returns: the directory components of the file
2351  *
2352  * Deprecated: use g_path_get_dirname() instead
2353  */
2354
2355 /**
2356  * g_path_get_dirname:
2357  * @file_name: the name of the file
2358  *
2359  * Gets the directory components of a file name.
2360  *
2361  * If the file name has no directory components "." is returned.
2362  * The returned string should be freed when no longer needed.
2363  *
2364  * Returns: the directory components of the file
2365  */
2366 gchar *
2367 g_path_get_dirname (const gchar *file_name)
2368 {
2369   gchar *base;
2370   gsize len;
2371
2372   g_return_val_if_fail (file_name != NULL, NULL);
2373
2374   base = strrchr (file_name, G_DIR_SEPARATOR);
2375
2376 #ifdef G_OS_WIN32
2377   {
2378     gchar *q;
2379     q = strrchr (file_name, '/');
2380     if (base == NULL || (q != NULL && q > base))
2381       base = q;
2382   }
2383 #endif
2384
2385   if (!base)
2386     {
2387 #ifdef G_OS_WIN32
2388       if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2389         {
2390           gchar drive_colon_dot[4];
2391
2392           drive_colon_dot[0] = file_name[0];
2393           drive_colon_dot[1] = ':';
2394           drive_colon_dot[2] = '.';
2395           drive_colon_dot[3] = '\0';
2396
2397           return g_strdup (drive_colon_dot);
2398         }
2399 #endif
2400     return g_strdup (".");
2401     }
2402
2403   while (base > file_name && G_IS_DIR_SEPARATOR (*base))
2404     base--;
2405
2406 #ifdef G_OS_WIN32
2407   /* base points to the char before the last slash.
2408    *
2409    * In case file_name is the root of a drive (X:\) or a child of the
2410    * root of a drive (X:\foo), include the slash.
2411    *
2412    * In case file_name is the root share of an UNC path
2413    * (\\server\share), add a slash, returning \\server\share\ .
2414    *
2415    * In case file_name is a direct child of a share in an UNC path
2416    * (\\server\share\foo), include the slash after the share name,
2417    * returning \\server\share\ .
2418    */
2419   if (base == file_name + 1 &&
2420       g_ascii_isalpha (file_name[0]) &&
2421       file_name[1] == ':')
2422     base++;
2423   else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2424            G_IS_DIR_SEPARATOR (file_name[1]) &&
2425            file_name[2] &&
2426            !G_IS_DIR_SEPARATOR (file_name[2]) &&
2427            base >= file_name + 2)
2428     {
2429       const gchar *p = file_name + 2;
2430       while (*p && !G_IS_DIR_SEPARATOR (*p))
2431         p++;
2432       if (p == base + 1)
2433         {
2434           len = (guint) strlen (file_name) + 1;
2435           base = g_new (gchar, len + 1);
2436           strcpy (base, file_name);
2437           base[len-1] = G_DIR_SEPARATOR;
2438           base[len] = 0;
2439           return base;
2440         }
2441       if (G_IS_DIR_SEPARATOR (*p))
2442         {
2443           p++;
2444           while (*p && !G_IS_DIR_SEPARATOR (*p))
2445             p++;
2446           if (p == base + 1)
2447             base++;
2448         }
2449     }
2450 #endif
2451
2452   len = (guint) 1 + base - file_name;
2453   base = g_new (gchar, len + 1);
2454   g_memmove (base, file_name, len);
2455   base[len] = 0;
2456
2457   return base;
2458 }
2459
2460 #if defined(MAXPATHLEN)
2461 #define G_PATH_LENGTH MAXPATHLEN
2462 #elif defined(PATH_MAX)
2463 #define G_PATH_LENGTH PATH_MAX
2464 #elif defined(_PC_PATH_MAX)
2465 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
2466 #else
2467 #define G_PATH_LENGTH 2048
2468 #endif
2469
2470 /**
2471  * g_get_current_dir:
2472  *
2473  * Gets the current directory.
2474  *
2475  * The returned string should be freed when no longer needed.
2476  * The encoding of the returned string is system defined.
2477  * On Windows, it is always UTF-8.
2478  *
2479  * Returns: the current directory
2480  */
2481 gchar *
2482 g_get_current_dir (void)
2483 {
2484 #ifdef G_OS_WIN32
2485
2486   gchar *dir = NULL;
2487   wchar_t dummy[2], *wdir;
2488   int len;
2489
2490   len = GetCurrentDirectoryW (2, dummy);
2491   wdir = g_new (wchar_t, len);
2492
2493   if (GetCurrentDirectoryW (len, wdir) == len - 1)
2494     dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
2495
2496   g_free (wdir);
2497
2498   if (dir == NULL)
2499     dir = g_strdup ("\\");
2500
2501   return dir;
2502
2503 #else
2504
2505   gchar *buffer = NULL;
2506   gchar *dir = NULL;
2507   static gulong max_len = 0;
2508
2509   if (max_len == 0)
2510     max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
2511
2512   /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
2513    * and, if that wasn't bad enough, hangs in doing so.
2514    */
2515 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
2516   buffer = g_new (gchar, max_len + 1);
2517   *buffer = 0;
2518   dir = getwd (buffer);
2519 #else
2520   while (max_len < G_MAXULONG / 2)
2521     {
2522       g_free (buffer);
2523       buffer = g_new (gchar, max_len + 1);
2524       *buffer = 0;
2525       dir = getcwd (buffer, max_len);
2526
2527       if (dir || errno != ERANGE)
2528         break;
2529
2530       max_len *= 2;
2531     }
2532 #endif  /* !sun || !HAVE_GETCWD */
2533
2534   if (!dir || !*buffer)
2535     {
2536       /* hm, should we g_error() out here?
2537        * this can happen if e.g. "./" has mode \0000
2538        */
2539       buffer[0] = G_DIR_SEPARATOR;
2540       buffer[1] = 0;
2541     }
2542
2543   dir = g_strdup (buffer);
2544   g_free (buffer);
2545
2546   return dir;
2547
2548 #endif /* !G_OS_WIN32 */
2549 }
2550
2551
2552 /* NOTE : Keep this part last to ensure nothing in this file uses thn
2553  * below binary compatibility versions.
2554  */
2555 #if defined (G_OS_WIN32) && !defined (_WIN64)
2556
2557 /* Binary compatibility versions. Will be called by code compiled
2558  * against quite old (pre-2.8, I think) headers only, not from more
2559  * recently compiled code.
2560  */
2561
2562 #undef g_file_test
2563
2564 gboolean
2565 g_file_test (const gchar *filename,
2566              GFileTest    test)
2567 {
2568   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
2569   gboolean retval;
2570
2571   if (utf8_filename == NULL)
2572     return FALSE;
2573
2574   retval = g_file_test_utf8 (utf8_filename, test);
2575
2576   g_free (utf8_filename);
2577
2578   return retval;
2579 }
2580
2581 #undef g_file_get_contents
2582
2583 gboolean
2584 g_file_get_contents (const gchar  *filename,
2585                      gchar       **contents,
2586                      gsize        *length,
2587                      GError      **error)
2588 {
2589   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
2590   gboolean retval;
2591
2592   if (utf8_filename == NULL)
2593     return FALSE;
2594
2595   retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
2596
2597   g_free (utf8_filename);
2598
2599   return retval;
2600 }
2601
2602 #undef g_mkstemp
2603
2604 gint
2605 g_mkstemp (gchar *tmpl)
2606 {
2607   /* This is the backward compatibility system codepage version,
2608    * thus use normal open().
2609    */
2610   return get_tmp_file (tmpl, (GTmpFileCallback) open,
2611                        O_RDWR | O_CREAT | O_EXCL, 0600);
2612 }
2613
2614 #undef g_file_open_tmp
2615
2616 gint
2617 g_file_open_tmp (const gchar  *tmpl,
2618                  gchar       **name_used,
2619                  GError      **error)
2620 {
2621   gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
2622   gchar *utf8_name_used;
2623   gint retval;
2624
2625   if (utf8_tmpl == NULL)
2626     return -1;
2627
2628   retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
2629   
2630   if (retval == -1)
2631     return -1;
2632
2633   if (name_used)
2634     *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
2635
2636   g_free (utf8_name_used);
2637
2638   return retval;
2639 }
2640
2641 #undef g_get_current_dir
2642
2643 gchar *
2644 g_get_current_dir (void)
2645 {
2646   gchar *utf8_dir = g_get_current_dir_utf8 ();
2647   gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
2648   g_free (utf8_dir);
2649   return dir;
2650 }
2651
2652 #endif
2653