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