Tizen 2.1 base
[platform/upstream/glib2.0.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       fclose (file);
1170       g_unlink (tmp_name);
1171       
1172       goto out;
1173     }
1174
1175   retval = g_strdup (tmp_name);
1176   
1177  out:
1178   g_free (tmp_name);
1179   g_free (display_name);
1180   
1181   return retval;
1182 }
1183
1184 /**
1185  * g_file_set_contents:
1186  * @filename: (type filename): name of a file to write @contents to, in the GLib file name
1187  *   encoding
1188  * @contents: (array length=length) (element-type guint8): string to write to the file
1189  * @length: length of @contents, or -1 if @contents is a nul-terminated string
1190  * @error: return location for a #GError, or %NULL
1191  *
1192  * Writes all of @contents to a file named @filename, with good error checking.
1193  * If a file called @filename already exists it will be overwritten.
1194  *
1195  * This write is atomic in the sense that it is first written to a temporary
1196  * file which is then renamed to the final name. Notes:
1197  * <itemizedlist>
1198  * <listitem>
1199  *    On Unix, if @filename already exists hard links to @filename will break.
1200  *    Also since the file is recreated, existing permissions, access control
1201  *    lists, metadata etc. may be lost. If @filename is a symbolic link,
1202  *    the link itself will be replaced, not the linked file.
1203  * </listitem>
1204  * <listitem>
1205  *   On Windows renaming a file will not remove an existing file with the
1206  *   new name, so on Windows there is a race condition between the existing
1207  *   file being removed and the temporary file being renamed.
1208  * </listitem>
1209  * <listitem>
1210  *   On Windows there is no way to remove a file that is open to some
1211  *   process, or mapped into memory. Thus, this function will fail if
1212  *   @filename already exists and is open.
1213  * </listitem>
1214  * </itemizedlist>
1215  *
1216  * If the call was successful, it returns %TRUE. If the call was not successful,
1217  * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
1218  * Possible error codes are those in the #GFileError enumeration.
1219  *
1220  * Note that the name for the temporary file is constructed by appending up
1221  * to 7 characters to @filename.
1222  *
1223  * Return value: %TRUE on success, %FALSE if an error occurred
1224  *
1225  * Since: 2.8
1226  **/
1227 gboolean
1228 g_file_set_contents (const gchar  *filename,
1229                      const gchar  *contents,
1230                      gssize        length,
1231                      GError      **error)
1232 {
1233   gchar *tmp_filename;
1234   gboolean retval;
1235   GError *rename_error = NULL;
1236   
1237   g_return_val_if_fail (filename != NULL, FALSE);
1238   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1239   g_return_val_if_fail (contents != NULL || length == 0, FALSE);
1240   g_return_val_if_fail (length >= -1, FALSE);
1241   
1242   if (length == -1)
1243     length = strlen (contents);
1244
1245   tmp_filename = write_to_temp_file (contents, length, filename, error);
1246   
1247   if (!tmp_filename)
1248     {
1249       retval = FALSE;
1250       goto out;
1251     }
1252
1253   if (!rename_file (tmp_filename, filename, &rename_error))
1254     {
1255 #ifndef G_OS_WIN32
1256
1257       g_unlink (tmp_filename);
1258       g_propagate_error (error, rename_error);
1259       retval = FALSE;
1260       goto out;
1261
1262 #else /* G_OS_WIN32 */
1263       
1264       /* Renaming failed, but on Windows this may just mean
1265        * the file already exists. So if the target file
1266        * exists, try deleting it and do the rename again.
1267        */
1268       if (!g_file_test (filename, G_FILE_TEST_EXISTS))
1269         {
1270           g_unlink (tmp_filename);
1271           g_propagate_error (error, rename_error);
1272           retval = FALSE;
1273           goto out;
1274         }
1275
1276       g_error_free (rename_error);
1277       
1278       if (g_unlink (filename) == -1)
1279         {
1280           gchar *display_filename = g_filename_display_name (filename);
1281
1282           int save_errno = errno;
1283           
1284           g_set_error (error,
1285                        G_FILE_ERROR,
1286                        g_file_error_from_errno (save_errno),
1287                        _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
1288                        display_filename,
1289                        g_strerror (save_errno));
1290
1291           g_free (display_filename);
1292           g_unlink (tmp_filename);
1293           retval = FALSE;
1294           goto out;
1295         }
1296       
1297       if (!rename_file (tmp_filename, filename, error))
1298         {
1299           g_unlink (tmp_filename);
1300           retval = FALSE;
1301           goto out;
1302         }
1303
1304 #endif
1305     }
1306
1307   retval = TRUE;
1308   
1309  out:
1310   g_free (tmp_filename);
1311   return retval;
1312 }
1313
1314 /*
1315  * get_tmp_file based on the mkstemp implementation from the GNU C library.
1316  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
1317  */
1318 typedef gint (*GTmpFileCallback) (gchar *, gint, gint);
1319
1320 static gint
1321 get_tmp_file (gchar            *tmpl,
1322               GTmpFileCallback  f,
1323               int               flags,
1324               int               mode)
1325 {
1326   char *XXXXXX;
1327   int count, fd;
1328   static const char letters[] =
1329     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1330   static const int NLETTERS = sizeof (letters) - 1;
1331   glong value;
1332   GTimeVal tv;
1333   static int counter = 0;
1334
1335   g_return_val_if_fail (tmpl != NULL, -1);
1336
1337   /* find the last occurrence of "XXXXXX" */
1338   XXXXXX = g_strrstr (tmpl, "XXXXXX");
1339
1340   if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
1341     {
1342       errno = EINVAL;
1343       return -1;
1344     }
1345
1346   /* Get some more or less random data.  */
1347   g_get_current_time (&tv);
1348   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
1349
1350   for (count = 0; count < 100; value += 7777, ++count)
1351     {
1352       glong v = value;
1353
1354       /* Fill in the random bits.  */
1355       XXXXXX[0] = letters[v % NLETTERS];
1356       v /= NLETTERS;
1357       XXXXXX[1] = letters[v % NLETTERS];
1358       v /= NLETTERS;
1359       XXXXXX[2] = letters[v % NLETTERS];
1360       v /= NLETTERS;
1361       XXXXXX[3] = letters[v % NLETTERS];
1362       v /= NLETTERS;
1363       XXXXXX[4] = letters[v % NLETTERS];
1364       v /= NLETTERS;
1365       XXXXXX[5] = letters[v % NLETTERS];
1366
1367       fd = f (tmpl, flags, mode);
1368
1369       if (fd >= 0)
1370         return fd;
1371       else if (errno != EEXIST)
1372         /* Any other error will apply also to other names we might
1373          *  try, and there are 2^32 or so of them, so give up now.
1374          */
1375         return -1;
1376     }
1377
1378   /* We got out of the loop because we ran out of combinations to try.  */
1379   errno = EEXIST;
1380   return -1;
1381 }
1382
1383 static gint
1384 wrap_mkdir (gchar *tmpl,
1385             int    flags G_GNUC_UNUSED,
1386             int    mode)
1387 {
1388   /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
1389   return g_mkdir (tmpl, mode);
1390 }
1391
1392 /**
1393  * g_mkdtemp_full:
1394  * @tmpl: (type filename): template directory name
1395  * @mode: permissions to create the temporary directory with
1396  *
1397  * Creates a temporary directory. See the mkdtemp() documentation
1398  * on most UNIX-like systems.
1399  *
1400  * The parameter is a string that should follow the rules for
1401  * mkdtemp() templates, i.e. contain the string "XXXXXX".
1402  * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1403  * sequence does not have to occur at the very end of the template
1404  * and you can pass a @mode. The X string will be modified to form
1405  * the name of a directory that didn't exist. The string should be
1406  * in the GLib file name encoding. Most importantly, on Windows it
1407  * should be in UTF-8.
1408  *
1409  * Return value: A pointer to @tmpl, which has been modified
1410  *     to hold the directory name. In case of errors, %NULL is
1411  *     returned, and %errno will be set.
1412  *
1413  * Since: 2.30
1414  */
1415 gchar *
1416 g_mkdtemp_full (gchar *tmpl,
1417                 gint   mode)
1418 {
1419   if (get_tmp_file (tmpl, wrap_mkdir, 0, mode) == -1)
1420     return NULL;
1421   else
1422     return tmpl;
1423 }
1424
1425 /**
1426  * g_mkdtemp:
1427  * @tmpl: (type filename): template directory name
1428  *
1429  * Creates a temporary directory. See the mkdtemp() documentation
1430  * on most UNIX-like systems.
1431  *
1432  * The parameter is a string that should follow the rules for
1433  * mkdtemp() templates, i.e. contain the string "XXXXXX".
1434  * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
1435  * sequence does not have to occur at the very end of the template
1436  * and you can pass a @mode and additional @flags. The X string will
1437  * be modified to form the name of a directory that didn't exist.
1438  * The string should be in the GLib file name encoding. Most importantly,
1439  * on Windows it should be in UTF-8.
1440  *
1441  * Return value: A pointer to @tmpl, which has been modified
1442  *     to hold the directory name.  In case of errors, %NULL is
1443  *     returned and %errno will be set.
1444  *
1445  * Since: 2.30
1446  */
1447 gchar *
1448 g_mkdtemp (gchar *tmpl)
1449 {
1450   return g_mkdtemp_full (tmpl, 0700);
1451 }
1452
1453 /**
1454  * g_mkstemp_full:
1455  * @tmpl: (type filename): template filename
1456  * @flags: flags to pass to an open() call in addition to O_EXCL
1457  *     and O_CREAT, which are passed automatically
1458  * @mode: permissions to create the temporary file with
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_full() is slightly more flexible than mkstemp()
1466  * in that the sequence does not have to occur at the very end of the
1467  * template and you can pass a @mode and additional @flags. The X
1468  * string will be modified to form the name of a file that didn't exist.
1469  * The string should be in the GLib file name encoding. Most importantly,
1470  * on Windows it should be in UTF-8.
1471  *
1472  * Return value: A file handle (as from open()) to the file
1473  *     opened for reading and writing. The file handle should be
1474  *     closed with close(). In case of errors, -1 is returned
1475  *     and %errno will be set.
1476  *
1477  * Since: 2.22
1478  */
1479 gint
1480 g_mkstemp_full (gchar *tmpl,
1481                 gint   flags,
1482                 gint   mode)
1483 {
1484   /* tmpl is in UTF-8 on Windows, thus use g_open() */
1485   return get_tmp_file (tmpl, (GTmpFileCallback) g_open,
1486                        flags | O_CREAT | O_EXCL, mode);
1487 }
1488
1489 /**
1490  * g_mkstemp:
1491  * @tmpl: (type filename): template filename
1492  *
1493  * Opens a temporary file. See the mkstemp() documentation
1494  * on most UNIX-like systems.
1495  *
1496  * The parameter is a string that should follow the rules for
1497  * mkstemp() templates, i.e. contain the string "XXXXXX".
1498  * g_mkstemp() is slightly more flexible than mkstemp() in that the
1499  * sequence does not have to occur at the very end of the template.
1500  * The X string will be modified to form the name of a file that
1501  * didn't exist. The string should be in the GLib file name encoding.
1502  * Most importantly, on Windows it should be in UTF-8.
1503  *
1504  * Return value: A file handle (as from open()) to the file
1505  *     opened for reading and writing. The file is opened in binary
1506  *     mode on platforms where there is a difference. The file handle
1507  *     should be closed with close(). In case of errors, -1 is
1508  *     returned and %errno will be set.
1509  */
1510 gint
1511 g_mkstemp (gchar *tmpl)
1512 {
1513   return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
1514 }
1515
1516 static gint
1517 g_get_tmp_name (const gchar      *tmpl,
1518                 gchar           **name_used,
1519                 GTmpFileCallback  f,
1520                 gint              flags,
1521                 gint              mode,
1522                 GError          **error)
1523 {
1524   int retval;
1525   const char *tmpdir;
1526   const char *sep;
1527   char *fulltemplate;
1528   const char *slash;
1529
1530   if (tmpl == NULL)
1531     tmpl = ".XXXXXX";
1532
1533   if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
1534 #ifdef G_OS_WIN32
1535       || (strchr (tmpl, '/') != NULL && (slash = "/"))
1536 #endif
1537       )
1538     {
1539       gchar *display_tmpl = g_filename_display_name (tmpl);
1540       char c[2];
1541       c[0] = *slash;
1542       c[1] = '\0';
1543
1544       g_set_error (error,
1545                    G_FILE_ERROR,
1546                    G_FILE_ERROR_FAILED,
1547                    _("Template '%s' invalid, should not contain a '%s'"),
1548                    display_tmpl, c);
1549       g_free (display_tmpl);
1550
1551       return -1;
1552     }
1553
1554   if (strstr (tmpl, "XXXXXX") == NULL)
1555     {
1556       gchar *display_tmpl = g_filename_display_name (tmpl);
1557       g_set_error (error,
1558                    G_FILE_ERROR,
1559                    G_FILE_ERROR_FAILED,
1560                    _("Template '%s' doesn't contain XXXXXX"),
1561                    display_tmpl);
1562       g_free (display_tmpl);
1563       return -1;
1564     }
1565
1566   tmpdir = g_get_tmp_dir ();
1567
1568   if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
1569     sep = "";
1570   else
1571     sep = G_DIR_SEPARATOR_S;
1572
1573   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
1574
1575   retval = get_tmp_file (fulltemplate, f, flags, mode);
1576   if (retval == -1)
1577     {
1578       int save_errno = errno;
1579       gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
1580
1581       g_set_error (error,
1582                    G_FILE_ERROR,
1583                    g_file_error_from_errno (save_errno),
1584                    _("Failed to create file '%s': %s"),
1585                    display_fulltemplate, g_strerror (save_errno));
1586       g_free (display_fulltemplate);
1587       g_free (fulltemplate);
1588       return -1;
1589     }
1590
1591   *name_used = fulltemplate;
1592
1593   return retval;
1594 }
1595
1596 /**
1597  * g_file_open_tmp:
1598  * @tmpl: (type filename) (allow-none): Template for file name, as in
1599  *     g_mkstemp(), basename only, or %NULL for a default template
1600  * @name_used: (out) (type filename): location to store actual name used,
1601  *     or %NULL
1602  * @error: return location for a #GError
1603  *
1604  * Opens a file for writing in the preferred directory for temporary
1605  * files (as returned by g_get_tmp_dir()).
1606  *
1607  * @tmpl should be a string in the GLib file name encoding containing
1608  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1609  * However, unlike these functions, the template should only be a
1610  * basename, no directory components are allowed. If template is
1611  * %NULL, a default template is used.
1612  *
1613  * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
1614  * modified, and might thus be a read-only literal string.
1615  *
1616  * Upon success, and if @name_used is non-%NULL, the actual name used
1617  * is returned in @name_used. This string should be freed with g_free()
1618  * when not needed any longer. The returned name is in the GLib file
1619  * name encoding.
1620  *
1621  * Return value: A file handle (as from open()) to the file opened for
1622  *     reading and writing. The file is opened in binary mode on platforms
1623  *     where there is a difference. The file handle should be closed with
1624  *     close(). In case of errors, -1 is returned and @error will be set.
1625  */
1626 gint
1627 g_file_open_tmp (const gchar  *tmpl,
1628                  gchar       **name_used,
1629                  GError      **error)
1630 {
1631   gchar *fulltemplate;
1632   gint result;
1633
1634   result = g_get_tmp_name (tmpl, &fulltemplate,
1635                            (GTmpFileCallback) g_open,
1636                            O_CREAT | O_EXCL | O_RDWR | O_BINARY,
1637                            0600,
1638                            error);
1639   if (result != -1)
1640     {
1641       if (name_used)
1642         *name_used = fulltemplate;
1643       else
1644         g_free (fulltemplate);
1645     }
1646
1647   return result;
1648 }
1649
1650 /**
1651  * g_dir_make_tmp:
1652  * @tmpl: (type filename) (allow-none): Template for directory name,
1653  *     as in g_mkdtemp(), basename only, or %NULL for a default template
1654  * @error: return location for a #GError
1655  *
1656  * Creates a subdirectory in the preferred directory for temporary
1657  * files (as returned by g_get_tmp_dir()).
1658  *
1659  * @tmpl should be a string in the GLib file name encoding containing
1660  * a sequence of six 'X' characters, as the parameter to g_mkstemp().
1661  * However, unlike these functions, the template should only be a
1662  * basename, no directory components are allowed. If template is
1663  * %NULL, a default template is used.
1664  *
1665  * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
1666  * modified, and might thus be a read-only literal string.
1667  *
1668  * Return value: (type filename): The actual name used. This string
1669  *     should be freed with g_free() when not needed any longer and is
1670  *     is in the GLib file name encoding. In case of errors, %NULL is
1671  *     returned and @error will be set.
1672  *
1673  * Since: 2.30
1674  */
1675 gchar *
1676 g_dir_make_tmp (const gchar  *tmpl,
1677                 GError      **error)
1678 {
1679   gchar *fulltemplate;
1680
1681   if (g_get_tmp_name (tmpl, &fulltemplate, wrap_mkdir, 0, 0700, error) == -1)
1682     return NULL;
1683   else
1684     return fulltemplate;
1685 }
1686
1687 static gchar *
1688 g_build_path_va (const gchar  *separator,
1689                  const gchar  *first_element,
1690                  va_list      *args,
1691                  gchar       **str_array)
1692 {
1693   GString *result;
1694   gint separator_len = strlen (separator);
1695   gboolean is_first = TRUE;
1696   gboolean have_leading = FALSE;
1697   const gchar *single_element = NULL;
1698   const gchar *next_element;
1699   const gchar *last_trailing = NULL;
1700   gint i = 0;
1701
1702   result = g_string_new (NULL);
1703
1704   if (str_array)
1705     next_element = str_array[i++];
1706   else
1707     next_element = first_element;
1708
1709   while (TRUE)
1710     {
1711       const gchar *element;
1712       const gchar *start;
1713       const gchar *end;
1714
1715       if (next_element)
1716         {
1717           element = next_element;
1718           if (str_array)
1719             next_element = str_array[i++];
1720           else
1721             next_element = va_arg (*args, gchar *);
1722         }
1723       else
1724         break;
1725
1726       /* Ignore empty elements */
1727       if (!*element)
1728         continue;
1729       
1730       start = element;
1731
1732       if (separator_len)
1733         {
1734           while (strncmp (start, separator, separator_len) == 0)
1735             start += separator_len;
1736         }
1737
1738       end = start + strlen (start);
1739       
1740       if (separator_len)
1741         {
1742           while (end >= start + separator_len &&
1743                  strncmp (end - separator_len, separator, separator_len) == 0)
1744             end -= separator_len;
1745           
1746           last_trailing = end;
1747           while (last_trailing >= element + separator_len &&
1748                  strncmp (last_trailing - separator_len, separator, separator_len) == 0)
1749             last_trailing -= separator_len;
1750
1751           if (!have_leading)
1752             {
1753               /* If the leading and trailing separator strings are in the
1754                * same element and overlap, the result is exactly that element
1755                */
1756               if (last_trailing <= start)
1757                 single_element = element;
1758                   
1759               g_string_append_len (result, element, start - element);
1760               have_leading = TRUE;
1761             }
1762           else
1763             single_element = NULL;
1764         }
1765
1766       if (end == start)
1767         continue;
1768
1769       if (!is_first)
1770         g_string_append (result, separator);
1771       
1772       g_string_append_len (result, start, end - start);
1773       is_first = FALSE;
1774     }
1775
1776   if (single_element)
1777     {
1778       g_string_free (result, TRUE);
1779       return g_strdup (single_element);
1780     }
1781   else
1782     {
1783       if (last_trailing)
1784         g_string_append (result, last_trailing);
1785   
1786       return g_string_free (result, FALSE);
1787     }
1788 }
1789
1790 /**
1791  * g_build_pathv:
1792  * @separator: a string used to separator the elements of the path.
1793  * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
1794  * 
1795  * Behaves exactly like g_build_path(), but takes the path elements 
1796  * as a string array, instead of varargs. This function is mainly
1797  * meant for language bindings.
1798  *
1799  * Return value: a newly-allocated string that must be freed with g_free().
1800  *
1801  * Since: 2.8
1802  */
1803 gchar *
1804 g_build_pathv (const gchar  *separator,
1805                gchar       **args)
1806 {
1807   if (!args)
1808     return NULL;
1809
1810   return g_build_path_va (separator, NULL, NULL, args);
1811 }
1812
1813
1814 /**
1815  * g_build_path:
1816  * @separator: a string used to separator the elements of the path.
1817  * @first_element: the first element in the path
1818  * @...: remaining elements in path, terminated by %NULL
1819  * 
1820  * Creates a path from a series of elements using @separator as the
1821  * separator between elements. At the boundary between two elements,
1822  * any trailing occurrences of separator in the first element, or
1823  * leading occurrences of separator in the second element are removed
1824  * and exactly one copy of the separator is inserted.
1825  *
1826  * Empty elements are ignored.
1827  *
1828  * The number of leading copies of the separator on the result is
1829  * the same as the number of leading copies of the separator on
1830  * the first non-empty element.
1831  *
1832  * The number of trailing copies of the separator on the result is
1833  * the same as the number of trailing copies of the separator on
1834  * the last non-empty element. (Determination of the number of
1835  * trailing copies is done without stripping leading copies, so
1836  * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
1837  * has 1 trailing copy.)
1838  *
1839  * However, if there is only a single non-empty element, and there
1840  * are no characters in that element not part of the leading or
1841  * trailing separators, then the result is exactly the original value
1842  * of that element.
1843  *
1844  * Other than for determination of the number of leading and trailing
1845  * copies of the separator, elements consisting only of copies
1846  * of the separator are ignored.
1847  * 
1848  * Return value: a newly-allocated string that must be freed with g_free().
1849  **/
1850 gchar *
1851 g_build_path (const gchar *separator,
1852               const gchar *first_element,
1853               ...)
1854 {
1855   gchar *str;
1856   va_list args;
1857
1858   g_return_val_if_fail (separator != NULL, NULL);
1859
1860   va_start (args, first_element);
1861   str = g_build_path_va (separator, first_element, &args, NULL);
1862   va_end (args);
1863
1864   return str;
1865 }
1866
1867 #ifdef G_OS_WIN32
1868
1869 static gchar *
1870 g_build_pathname_va (const gchar  *first_element,
1871                      va_list      *args,
1872                      gchar       **str_array)
1873 {
1874   /* Code copied from g_build_pathv(), and modified to use two
1875    * alternative single-character separators.
1876    */
1877   GString *result;
1878   gboolean is_first = TRUE;
1879   gboolean have_leading = FALSE;
1880   const gchar *single_element = NULL;
1881   const gchar *next_element;
1882   const gchar *last_trailing = NULL;
1883   gchar current_separator = '\\';
1884   gint i = 0;
1885
1886   result = g_string_new (NULL);
1887
1888   if (str_array)
1889     next_element = str_array[i++];
1890   else
1891     next_element = first_element;
1892   
1893   while (TRUE)
1894     {
1895       const gchar *element;
1896       const gchar *start;
1897       const gchar *end;
1898
1899       if (next_element)
1900         {
1901           element = next_element;
1902           if (str_array)
1903             next_element = str_array[i++];
1904           else
1905             next_element = va_arg (*args, gchar *);
1906         }
1907       else
1908         break;
1909
1910       /* Ignore empty elements */
1911       if (!*element)
1912         continue;
1913       
1914       start = element;
1915
1916       if (TRUE)
1917         {
1918           while (start &&
1919                  (*start == '\\' || *start == '/'))
1920             {
1921               current_separator = *start;
1922               start++;
1923             }
1924         }
1925
1926       end = start + strlen (start);
1927       
1928       if (TRUE)
1929         {
1930           while (end >= start + 1 &&
1931                  (end[-1] == '\\' || end[-1] == '/'))
1932             {
1933               current_separator = end[-1];
1934               end--;
1935             }
1936           
1937           last_trailing = end;
1938           while (last_trailing >= element + 1 &&
1939                  (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
1940             last_trailing--;
1941
1942           if (!have_leading)
1943             {
1944               /* If the leading and trailing separator strings are in the
1945                * same element and overlap, the result is exactly that element
1946                */
1947               if (last_trailing <= start)
1948                 single_element = element;
1949                   
1950               g_string_append_len (result, element, start - element);
1951               have_leading = TRUE;
1952             }
1953           else
1954             single_element = NULL;
1955         }
1956
1957       if (end == start)
1958         continue;
1959
1960       if (!is_first)
1961         g_string_append_len (result, &current_separator, 1);
1962       
1963       g_string_append_len (result, start, end - start);
1964       is_first = FALSE;
1965     }
1966
1967   if (single_element)
1968     {
1969       g_string_free (result, TRUE);
1970       return g_strdup (single_element);
1971     }
1972   else
1973     {
1974       if (last_trailing)
1975         g_string_append (result, last_trailing);
1976   
1977       return g_string_free (result, FALSE);
1978     }
1979 }
1980
1981 #endif
1982
1983 /**
1984  * g_build_filenamev:
1985  * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
1986  * 
1987  * Behaves exactly like g_build_filename(), but takes the path elements 
1988  * as a string array, instead of varargs. This function is mainly
1989  * meant for language bindings.
1990  *
1991  * Return value: a newly-allocated string that must be freed with g_free().
1992  * 
1993  * Since: 2.8
1994  */
1995 gchar *
1996 g_build_filenamev (gchar **args)
1997 {
1998   gchar *str;
1999
2000 #ifndef G_OS_WIN32
2001   str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
2002 #else
2003   str = g_build_pathname_va (NULL, NULL, args);
2004 #endif
2005
2006   return str;
2007 }
2008
2009 /**
2010  * g_build_filename:
2011  * @first_element: the first element in the path
2012  * @...: remaining elements in path, terminated by %NULL
2013  * 
2014  * Creates a filename from a series of elements using the correct
2015  * separator for filenames.
2016  *
2017  * On Unix, this function behaves identically to <literal>g_build_path
2018  * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
2019  *
2020  * On Windows, it takes into account that either the backslash
2021  * (<literal>\</literal> or slash (<literal>/</literal>) can be used
2022  * as separator in filenames, but otherwise behaves as on Unix. When
2023  * file pathname separators need to be inserted, the one that last
2024  * previously occurred in the parameters (reading from left to right)
2025  * is used.
2026  *
2027  * No attempt is made to force the resulting filename to be an absolute
2028  * path. If the first element is a relative path, the result will
2029  * be a relative path. 
2030  * 
2031  * Return value: a newly-allocated string that must be freed with g_free().
2032  **/
2033 gchar *
2034 g_build_filename (const gchar *first_element, 
2035                   ...)
2036 {
2037   gchar *str;
2038   va_list args;
2039
2040   va_start (args, first_element);
2041 #ifndef G_OS_WIN32
2042   str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
2043 #else
2044   str = g_build_pathname_va (first_element, &args, NULL);
2045 #endif
2046   va_end (args);
2047
2048   return str;
2049 }
2050
2051 /**
2052  * g_file_read_link:
2053  * @filename: the symbolic link
2054  * @error: return location for a #GError
2055  *
2056  * Reads the contents of the symbolic link @filename like the POSIX
2057  * readlink() function.  The returned string is in the encoding used
2058  * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
2059  *
2060  * Returns: A newly-allocated string with the contents of the symbolic link, 
2061  *          or %NULL if an error occurred.
2062  *
2063  * Since: 2.4
2064  */
2065 gchar *
2066 g_file_read_link (const gchar  *filename,
2067                   GError      **error)
2068 {
2069 #ifdef HAVE_READLINK
2070   gchar *buffer;
2071   guint size;
2072   gint read_size;    
2073   
2074   size = 256; 
2075   buffer = g_malloc (size);
2076   
2077   while (TRUE) 
2078     {
2079       read_size = readlink (filename, buffer, size);
2080       if (read_size < 0) {
2081         int save_errno = errno;
2082         gchar *display_filename = g_filename_display_name (filename);
2083
2084         g_free (buffer);
2085         g_set_error (error,
2086                      G_FILE_ERROR,
2087                      g_file_error_from_errno (save_errno),
2088                      _("Failed to read the symbolic link '%s': %s"),
2089                      display_filename, 
2090                      g_strerror (save_errno));
2091         g_free (display_filename);
2092         
2093         return NULL;
2094       }
2095     
2096       if (read_size < size) 
2097         {
2098           buffer[read_size] = 0;
2099           return buffer;
2100         }
2101       
2102       size *= 2;
2103       buffer = g_realloc (buffer, size);
2104     }
2105 #else
2106   g_set_error_literal (error,
2107                        G_FILE_ERROR,
2108                        G_FILE_ERROR_INVAL,
2109                        _("Symbolic links not supported"));
2110         
2111   return NULL;
2112 #endif
2113 }
2114
2115 /**
2116  * g_path_is_absolute:
2117  * @file_name: a file name
2118  *
2119  * Returns %TRUE if the given @file_name is an absolute file name.
2120  * Note that this is a somewhat vague concept on Windows.
2121  *
2122  * On POSIX systems, an absolute file name is well-defined. It always
2123  * starts from the single root directory. For example "/usr/local".
2124  *
2125  * On Windows, the concepts of current drive and drive-specific
2126  * current directory introduce vagueness. This function interprets as
2127  * an absolute file name one that either begins with a directory
2128  * separator such as "\Users\tml" or begins with the root on a drive,
2129  * for example "C:\Windows". The first case also includes UNC paths
2130  * such as "\\myserver\docs\foo". In all cases, either slashes or
2131  * backslashes are accepted.
2132  *
2133  * Note that a file name relative to the current drive root does not
2134  * truly specify a file uniquely over time and across processes, as
2135  * the current drive is a per-process value and can be changed.
2136  *
2137  * File names relative the current directory on some specific drive,
2138  * such as "D:foo/bar", are not interpreted as absolute by this
2139  * function, but they obviously are not relative to the normal current
2140  * directory as returned by getcwd() or g_get_current_dir()
2141  * either. Such paths should be avoided, or need to be handled using
2142  * Windows-specific code.
2143  *
2144  * Returns: %TRUE if @file_name is absolute
2145  */
2146 gboolean
2147 g_path_is_absolute (const gchar *file_name)
2148 {
2149   g_return_val_if_fail (file_name != NULL, FALSE);
2150
2151   if (G_IS_DIR_SEPARATOR (file_name[0]))
2152     return TRUE;
2153
2154 #ifdef G_OS_WIN32
2155   /* Recognize drive letter on native Windows */
2156   if (g_ascii_isalpha (file_name[0]) &&
2157       file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
2158     return TRUE;
2159 #endif
2160
2161   return FALSE;
2162 }
2163
2164 /**
2165  * g_path_skip_root:
2166  * @file_name: a file name
2167  *
2168  * Returns a pointer into @file_name after the root component,
2169  * i.e. after the "/" in UNIX or "C:\" under Windows. If @file_name
2170  * is not an absolute path it returns %NULL.
2171  *
2172  * Returns: a pointer into @file_name after the root component
2173  */
2174 const gchar *
2175 g_path_skip_root (const gchar *file_name)
2176 {
2177   g_return_val_if_fail (file_name != NULL, NULL);
2178
2179 #ifdef G_PLATFORM_WIN32
2180   /* Skip \\server\share or //server/share */
2181   if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2182       G_IS_DIR_SEPARATOR (file_name[1]) &&
2183       file_name[2] &&
2184       !G_IS_DIR_SEPARATOR (file_name[2]))
2185     {
2186       gchar *p;
2187       p = strchr (file_name + 2, G_DIR_SEPARATOR);
2188
2189 #ifdef G_OS_WIN32
2190       {
2191         gchar *q;
2192
2193         q = strchr (file_name + 2, '/');
2194         if (p == NULL || (q != NULL && q < p))
2195         p = q;
2196       }
2197 #endif
2198
2199       if (p && p > file_name + 2 && p[1])
2200         {
2201           file_name = p + 1;
2202
2203           while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
2204             file_name++;
2205
2206           /* Possibly skip a backslash after the share name */
2207           if (G_IS_DIR_SEPARATOR (file_name[0]))
2208             file_name++;
2209
2210           return (gchar *)file_name;
2211         }
2212     }
2213 #endif
2214
2215   /* Skip initial slashes */
2216   if (G_IS_DIR_SEPARATOR (file_name[0]))
2217     {
2218       while (G_IS_DIR_SEPARATOR (file_name[0]))
2219         file_name++;
2220       return (gchar *)file_name;
2221     }
2222
2223 #ifdef G_OS_WIN32
2224   /* Skip X:\ */
2225   if (g_ascii_isalpha (file_name[0]) &&
2226       file_name[1] == ':' &&
2227       G_IS_DIR_SEPARATOR (file_name[2]))
2228     return (gchar *)file_name + 3;
2229 #endif
2230
2231   return NULL;
2232 }
2233
2234 /**
2235  * g_basename:
2236  * @file_name: the name of the file
2237  *
2238  * Gets the name of the file without any leading directory
2239  * components. It returns a pointer into the given file name
2240  * string.
2241  *
2242  * Return value: the name of the file without any leading
2243  *     directory components
2244  *
2245  * Deprecated:2.2: Use g_path_get_basename() instead, but notice
2246  *     that g_path_get_basename() allocates new memory for the
2247  *     returned string, unlike this function which returns a pointer
2248  *     into the argument.
2249  */
2250 const gchar *
2251 g_basename (const gchar *file_name)
2252 {
2253   gchar *base;
2254
2255   g_return_val_if_fail (file_name != NULL, NULL);
2256
2257   base = strrchr (file_name, G_DIR_SEPARATOR);
2258
2259 #ifdef G_OS_WIN32
2260   {
2261     gchar *q;
2262     q = strrchr (file_name, '/');
2263     if (base == NULL || (q != NULL && q > base))
2264       base = q;
2265   }
2266 #endif
2267
2268   if (base)
2269     return base + 1;
2270
2271 #ifdef G_OS_WIN32
2272   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2273     return (gchar*) file_name + 2;
2274 #endif
2275
2276   return (gchar*) file_name;
2277 }
2278
2279 /**
2280  * g_path_get_basename:
2281  * @file_name: the name of the file
2282  *
2283  * Gets the last component of the filename.
2284  *
2285  * If @file_name ends with a directory separator it gets the component
2286  * before the last slash. If @file_name consists only of directory
2287  * separators (and on Windows, possibly a drive letter), a single
2288  * separator is returned. If @file_name is empty, it gets ".".
2289  *
2290  * Return value: a newly allocated string containing the last
2291  *    component of the filename
2292  */
2293 gchar *
2294 g_path_get_basename (const gchar *file_name)
2295 {
2296   gssize base;
2297   gssize last_nonslash;
2298   gsize len;
2299   gchar *retval;
2300
2301   g_return_val_if_fail (file_name != NULL, NULL);
2302
2303   if (file_name[0] == '\0')
2304     return g_strdup (".");
2305
2306   last_nonslash = strlen (file_name) - 1;
2307
2308   while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
2309     last_nonslash--;
2310
2311   if (last_nonslash == -1)
2312     /* string only containing slashes */
2313     return g_strdup (G_DIR_SEPARATOR_S);
2314
2315 #ifdef G_OS_WIN32
2316   if (last_nonslash == 1 &&
2317       g_ascii_isalpha (file_name[0]) &&
2318       file_name[1] == ':')
2319     /* string only containing slashes and a drive */
2320     return g_strdup (G_DIR_SEPARATOR_S);
2321 #endif
2322   base = last_nonslash;
2323
2324   while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
2325     base--;
2326
2327 #ifdef G_OS_WIN32
2328   if (base == -1 &&
2329       g_ascii_isalpha (file_name[0]) &&
2330       file_name[1] == ':')
2331     base = 1;
2332 #endif /* G_OS_WIN32 */
2333
2334   len = last_nonslash - base;
2335   retval = g_malloc (len + 1);
2336   memcpy (retval, file_name + base + 1, len);
2337   retval [len] = '\0';
2338
2339   return retval;
2340 }
2341
2342 /**
2343  * g_dirname:
2344  * @file_name: the name of the file
2345  *
2346  * Gets the directory components of a file name.
2347  *
2348  * If the file name has no directory components "." is returned.
2349  * The returned string should be freed when no longer needed.
2350  *
2351  * Returns: the directory components of the file
2352  *
2353  * Deprecated: use g_path_get_dirname() instead
2354  */
2355
2356 /**
2357  * g_path_get_dirname:
2358  * @file_name: the name of the file
2359  *
2360  * Gets the directory components of a file name.
2361  *
2362  * If the file name has no directory components "." is returned.
2363  * The returned string should be freed when no longer needed.
2364  *
2365  * Returns: the directory components of the file
2366  */
2367 gchar *
2368 g_path_get_dirname (const gchar *file_name)
2369 {
2370   gchar *base;
2371   gsize len;
2372
2373   g_return_val_if_fail (file_name != NULL, NULL);
2374
2375   base = strrchr (file_name, G_DIR_SEPARATOR);
2376
2377 #ifdef G_OS_WIN32
2378   {
2379     gchar *q;
2380     q = strrchr (file_name, '/');
2381     if (base == NULL || (q != NULL && q > base))
2382       base = q;
2383   }
2384 #endif
2385
2386   if (!base)
2387     {
2388 #ifdef G_OS_WIN32
2389       if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
2390         {
2391           gchar drive_colon_dot[4];
2392
2393           drive_colon_dot[0] = file_name[0];
2394           drive_colon_dot[1] = ':';
2395           drive_colon_dot[2] = '.';
2396           drive_colon_dot[3] = '\0';
2397
2398           return g_strdup (drive_colon_dot);
2399         }
2400 #endif
2401     return g_strdup (".");
2402     }
2403
2404   while (base > file_name && G_IS_DIR_SEPARATOR (*base))
2405     base--;
2406
2407 #ifdef G_OS_WIN32
2408   /* base points to the char before the last slash.
2409    *
2410    * In case file_name is the root of a drive (X:\) or a child of the
2411    * root of a drive (X:\foo), include the slash.
2412    *
2413    * In case file_name is the root share of an UNC path
2414    * (\\server\share), add a slash, returning \\server\share\ .
2415    *
2416    * In case file_name is a direct child of a share in an UNC path
2417    * (\\server\share\foo), include the slash after the share name,
2418    * returning \\server\share\ .
2419    */
2420   if (base == file_name + 1 &&
2421       g_ascii_isalpha (file_name[0]) &&
2422       file_name[1] == ':')
2423     base++;
2424   else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
2425            G_IS_DIR_SEPARATOR (file_name[1]) &&
2426            file_name[2] &&
2427            !G_IS_DIR_SEPARATOR (file_name[2]) &&
2428            base >= file_name + 2)
2429     {
2430       const gchar *p = file_name + 2;
2431       while (*p && !G_IS_DIR_SEPARATOR (*p))
2432         p++;
2433       if (p == base + 1)
2434         {
2435           len = (guint) strlen (file_name) + 1;
2436           base = g_new (gchar, len + 1);
2437           strcpy (base, file_name);
2438           base[len-1] = G_DIR_SEPARATOR;
2439           base[len] = 0;
2440           return base;
2441         }
2442       if (G_IS_DIR_SEPARATOR (*p))
2443         {
2444           p++;
2445           while (*p && !G_IS_DIR_SEPARATOR (*p))
2446             p++;
2447           if (p == base + 1)
2448             base++;
2449         }
2450     }
2451 #endif
2452
2453   len = (guint) 1 + base - file_name;
2454   base = g_new (gchar, len + 1);
2455   g_memmove (base, file_name, len);
2456   base[len] = 0;
2457
2458   return base;
2459 }
2460
2461 #if defined(MAXPATHLEN)
2462 #define G_PATH_LENGTH MAXPATHLEN
2463 #elif defined(PATH_MAX)
2464 #define G_PATH_LENGTH PATH_MAX
2465 #elif defined(_PC_PATH_MAX)
2466 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
2467 #else
2468 #define G_PATH_LENGTH 2048
2469 #endif
2470
2471 /**
2472  * g_get_current_dir:
2473  *
2474  * Gets the current directory.
2475  *
2476  * The returned string should be freed when no longer needed.
2477  * The encoding of the returned string is system defined.
2478  * On Windows, it is always UTF-8.
2479  *
2480  * Returns: the current directory
2481  */
2482 gchar *
2483 g_get_current_dir (void)
2484 {
2485 #ifdef G_OS_WIN32
2486
2487   gchar *dir = NULL;
2488   wchar_t dummy[2], *wdir;
2489   int len;
2490
2491   len = GetCurrentDirectoryW (2, dummy);
2492   wdir = g_new (wchar_t, len);
2493
2494   if (GetCurrentDirectoryW (len, wdir) == len - 1)
2495     dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
2496
2497   g_free (wdir);
2498
2499   if (dir == NULL)
2500     dir = g_strdup ("\\");
2501
2502   return dir;
2503
2504 #else
2505
2506   gchar *buffer = NULL;
2507   gchar *dir = NULL;
2508   static gulong max_len = 0;
2509
2510   if (max_len == 0)
2511     max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
2512
2513   /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
2514    * and, if that wasn't bad enough, hangs in doing so.
2515    */
2516 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
2517   buffer = g_new (gchar, max_len + 1);
2518   *buffer = 0;
2519   dir = getwd (buffer);
2520 #else
2521   while (max_len < G_MAXULONG / 2)
2522     {
2523       g_free (buffer);
2524       buffer = g_new (gchar, max_len + 1);
2525       *buffer = 0;
2526       dir = getcwd (buffer, max_len);
2527
2528       if (dir || errno != ERANGE)
2529         break;
2530
2531       max_len *= 2;
2532     }
2533 #endif  /* !sun || !HAVE_GETCWD */
2534
2535   if (!dir || !*buffer)
2536     {
2537       /* hm, should we g_error() out here?
2538        * this can happen if e.g. "./" has mode \0000
2539        */
2540       buffer[0] = G_DIR_SEPARATOR;
2541       buffer[1] = 0;
2542     }
2543
2544   dir = g_strdup (buffer);
2545   g_free (buffer);
2546
2547   return dir;
2548
2549 #endif /* !G_OS_WIN32 */
2550 }
2551
2552
2553 /* NOTE : Keep this part last to ensure nothing in this file uses thn
2554  * below binary compatibility versions.
2555  */
2556 #if defined (G_OS_WIN32) && !defined (_WIN64)
2557
2558 /* Binary compatibility versions. Will be called by code compiled
2559  * against quite old (pre-2.8, I think) headers only, not from more
2560  * recently compiled code.
2561  */
2562
2563 #undef g_file_test
2564
2565 gboolean
2566 g_file_test (const gchar *filename,
2567              GFileTest    test)
2568 {
2569   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
2570   gboolean retval;
2571
2572   if (utf8_filename == NULL)
2573     return FALSE;
2574
2575   retval = g_file_test_utf8 (utf8_filename, test);
2576
2577   g_free (utf8_filename);
2578
2579   return retval;
2580 }
2581
2582 #undef g_file_get_contents
2583
2584 gboolean
2585 g_file_get_contents (const gchar  *filename,
2586                      gchar       **contents,
2587                      gsize        *length,
2588                      GError      **error)
2589 {
2590   gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
2591   gboolean retval;
2592
2593   if (utf8_filename == NULL)
2594     return FALSE;
2595
2596   retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
2597
2598   g_free (utf8_filename);
2599
2600   return retval;
2601 }
2602
2603 #undef g_mkstemp
2604
2605 gint
2606 g_mkstemp (gchar *tmpl)
2607 {
2608   /* This is the backward compatibility system codepage version,
2609    * thus use normal open().
2610    */
2611   return get_tmp_file (tmpl, (GTmpFileCallback) open,
2612                        O_RDWR | O_CREAT | O_EXCL, 0600);
2613 }
2614
2615 #undef g_file_open_tmp
2616
2617 gint
2618 g_file_open_tmp (const gchar  *tmpl,
2619                  gchar       **name_used,
2620                  GError      **error)
2621 {
2622   gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
2623   gchar *utf8_name_used;
2624   gint retval;
2625
2626   if (utf8_tmpl == NULL)
2627     return -1;
2628
2629   retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
2630   
2631   if (retval == -1)
2632     return -1;
2633
2634   if (name_used)
2635     *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
2636
2637   g_free (utf8_name_used);
2638
2639   return retval;
2640 }
2641
2642 #undef g_get_current_dir
2643
2644 gchar *
2645 g_get_current_dir (void)
2646 {
2647   gchar *utf8_dir = g_get_current_dir_utf8 ();
2648   gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
2649   g_free (utf8_dir);
2650   return dir;
2651 }
2652
2653 #endif
2654