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