Extended documentation.
[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
23 #include "glib.h"
24
25 #include <sys/stat.h>
26 #ifdef HAVE_UNISTD_H
27 #include <unistd.h>
28 #endif
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <string.h>
33 #include <errno.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <fcntl.h>
37 #include <stdlib.h>
38
39 #ifdef G_OS_WIN32
40 #include <io.h>
41 #ifndef F_OK
42 #define F_OK 0
43 #define X_OK 1
44 #define W_OK 2
45 #define R_OK 4
46 #endif /* !F_OK */
47
48 #ifndef S_ISREG
49 #define S_ISREG(mode) ((mode)&_S_IFREG)
50 #endif
51
52 #ifndef S_ISDIR
53 #define S_ISDIR(mode) ((mode)&_S_IFDIR)
54 #endif
55
56 #endif /* G_OS_WIN32 */
57
58 #ifndef S_ISLNK
59 #define S_ISLNK(x) 0
60 #endif
61
62 #ifndef O_BINARY
63 #define O_BINARY 0
64 #endif
65
66 #include "glibintl.h"
67
68 /**
69  * g_file_test:
70  * @filename: a filename to test
71  * @test: bitfield of #GFileTest flags
72  * 
73  * Returns %TRUE if any of the tests in the bitfield @test are
74  * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS | 
75  * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists; 
76  * the check whether it's a directory doesn't matter since the existence 
77  * test is %TRUE. With the current set of available tests, there's no point
78  * passing in more than one test at a time.
79  * 
80  * Apart from #G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
81  * so for a symbolic link to a regular file g_file_test() will return
82  * %TRUE for both #G_FILE_TEST_IS_SYMLINK and #G_FILE_TEST_IS_REGULAR.
83  *
84  * Note, that for a dangling symbolic link g_file_test() will return
85  * %TRUE for #G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
86  *
87  * Return value: whether a test was %TRUE
88  **/
89 gboolean
90 g_file_test (const gchar *filename,
91              GFileTest    test)
92 {
93   if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
94     return TRUE;
95   
96   if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
97     return TRUE;
98
99   if (test & G_FILE_TEST_IS_SYMLINK)
100     {
101       struct stat s;
102
103       if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
104         return TRUE;
105     }
106   
107   if (test & (G_FILE_TEST_IS_REGULAR | G_FILE_TEST_IS_DIR))
108     {
109       struct stat s;
110       
111       if (stat (filename, &s) == 0)
112         {
113           if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
114             return TRUE;
115           
116           if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
117             return TRUE;
118         }
119     }
120
121   return FALSE;
122 }
123
124 GQuark
125 g_file_error_quark (void)
126 {
127   static GQuark q = 0;
128   if (q == 0)
129     q = g_quark_from_static_string ("g-file-error-quark");
130
131   return q;
132 }
133
134 /**
135  * g_file_error_from_errno:
136  * @err_no: an "errno" value
137  * 
138  * Gets a #GFileError constant based on the passed-in @errno.
139  * For example, if you pass in %EEXIST this function returns
140  * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
141  * assume that all #GFileError values will exist.
142  *
143  * Normally a #GFileError value goes into a #GError returned
144  * from a function that manipulates files. So you would use
145  * g_file_error_from_errno() when constructing a #GError.
146  * 
147  * Return value: #GFileError corresponding to the given @errno
148  **/
149 GFileError
150 g_file_error_from_errno (gint err_no)
151 {
152   switch (err_no)
153     {
154 #ifdef EEXIST
155     case EEXIST:
156       return G_FILE_ERROR_EXIST;
157       break;
158 #endif
159
160 #ifdef EISDIR
161     case EISDIR:
162       return G_FILE_ERROR_ISDIR;
163       break;
164 #endif
165
166 #ifdef EACCES
167     case EACCES:
168       return G_FILE_ERROR_ACCES;
169       break;
170 #endif
171
172 #ifdef ENAMETOOLONG
173     case ENAMETOOLONG:
174       return G_FILE_ERROR_NAMETOOLONG;
175       break;
176 #endif
177
178 #ifdef ENOENT
179     case ENOENT:
180       return G_FILE_ERROR_NOENT;
181       break;
182 #endif
183
184 #ifdef ENOTDIR
185     case ENOTDIR:
186       return G_FILE_ERROR_NOTDIR;
187       break;
188 #endif
189
190 #ifdef ENXIO
191     case ENXIO:
192       return G_FILE_ERROR_NXIO;
193       break;
194 #endif
195
196 #ifdef ENODEV
197     case ENODEV:
198       return G_FILE_ERROR_NODEV;
199       break;
200 #endif
201
202 #ifdef EROFS
203     case EROFS:
204       return G_FILE_ERROR_ROFS;
205       break;
206 #endif
207
208 #ifdef ETXTBSY
209     case ETXTBSY:
210       return G_FILE_ERROR_TXTBSY;
211       break;
212 #endif
213
214 #ifdef EFAULT
215     case EFAULT:
216       return G_FILE_ERROR_FAULT;
217       break;
218 #endif
219
220 #ifdef ELOOP
221     case ELOOP:
222       return G_FILE_ERROR_LOOP;
223       break;
224 #endif
225
226 #ifdef ENOSPC
227     case ENOSPC:
228       return G_FILE_ERROR_NOSPC;
229       break;
230 #endif
231
232 #ifdef ENOMEM
233     case ENOMEM:
234       return G_FILE_ERROR_NOMEM;
235       break;
236 #endif
237
238 #ifdef EMFILE
239     case EMFILE:
240       return G_FILE_ERROR_MFILE;
241       break;
242 #endif
243
244 #ifdef ENFILE
245     case ENFILE:
246       return G_FILE_ERROR_NFILE;
247       break;
248 #endif
249
250 #ifdef EBADF
251     case EBADF:
252       return G_FILE_ERROR_BADF;
253       break;
254 #endif
255
256 #ifdef EINVAL
257     case EINVAL:
258       return G_FILE_ERROR_INVAL;
259       break;
260 #endif
261
262 #ifdef EPIPE
263     case EPIPE:
264       return G_FILE_ERROR_PIPE;
265       break;
266 #endif
267
268 #ifdef EAGAIN
269     case EAGAIN:
270       return G_FILE_ERROR_AGAIN;
271       break;
272 #endif
273
274 #ifdef EINTR
275     case EINTR:
276       return G_FILE_ERROR_INTR;
277       break;
278 #endif
279
280 #ifdef EIO
281     case EIO:
282       return G_FILE_ERROR_IO;
283       break;
284 #endif
285
286 #ifdef EPERM
287     case EPERM:
288       return G_FILE_ERROR_PERM;
289       break;
290 #endif
291       
292     default:
293       return G_FILE_ERROR_FAILED;
294       break;
295     }
296 }
297
298 static gboolean
299 get_contents_stdio (const gchar *filename,
300                     FILE        *f,
301                     gchar      **contents,
302                     gsize       *length, 
303                     GError     **error)
304 {
305   gchar buf[2048];
306   size_t bytes;
307   char *str;
308   size_t total_bytes;
309   size_t total_allocated;
310   
311   g_assert (f != NULL);
312
313 #define STARTING_ALLOC 64
314   
315   total_bytes = 0;
316   total_allocated = STARTING_ALLOC;
317   str = g_malloc (STARTING_ALLOC);
318   
319   while (!feof (f))
320     {
321       bytes = fread (buf, 1, 2048, f);
322
323       while ((total_bytes + bytes + 1) > total_allocated)
324         {
325           total_allocated *= 2;
326           str = g_try_realloc (str, total_allocated);
327
328           if (str == NULL)
329             {
330               g_set_error (error,
331                            G_FILE_ERROR,
332                            G_FILE_ERROR_NOMEM,
333                            _("Could not allocate %lu bytes to read file \"%s\""),
334                            (gulong) total_allocated, filename);
335               goto error;
336             }
337         }
338       
339       if (ferror (f))
340         {
341           g_set_error (error,
342                        G_FILE_ERROR,
343                        g_file_error_from_errno (errno),
344                        _("Error reading file '%s': %s"),
345                        filename, strerror (errno));
346
347           goto error;
348         }
349
350       memcpy (str + total_bytes, buf, bytes);
351       total_bytes += bytes;
352     }
353
354   fclose (f);
355
356   str[total_bytes] = '\0';
357   
358   if (length)
359     *length = total_bytes;
360   
361   *contents = str;
362   
363   return TRUE;
364
365  error:
366
367   g_free (str);
368   fclose (f);
369   
370   return FALSE;  
371 }
372
373 #ifndef G_OS_WIN32
374
375 static gboolean
376 get_contents_regfile (const gchar *filename,
377                       struct stat *stat_buf,
378                       gint         fd,
379                       gchar      **contents,
380                       gsize       *length,
381                       GError     **error)
382 {
383   gchar *buf;
384   size_t bytes_read;
385   size_t size;
386   size_t alloc_size;
387   
388   size = stat_buf->st_size;
389
390   alloc_size = size + 1;
391   buf = g_try_malloc (alloc_size);
392
393   if (buf == NULL)
394     {
395       g_set_error (error,
396                    G_FILE_ERROR,
397                    G_FILE_ERROR_NOMEM,
398                    _("Could not allocate %lu bytes to read file \"%s\""),
399                    (gulong) alloc_size, filename);
400
401       return FALSE;
402     }
403   
404   bytes_read = 0;
405   while (bytes_read < size)
406     {
407       gssize rc;
408           
409       rc = read (fd, buf + bytes_read, size - bytes_read);
410
411       if (rc < 0)
412         {
413           if (errno != EINTR) 
414             {
415               close (fd);
416
417               g_free (buf);
418                   
419               g_set_error (error,
420                            G_FILE_ERROR,
421                            g_file_error_from_errno (errno),
422                            _("Failed to read from file '%s': %s"),
423                            filename, strerror (errno));
424
425               return FALSE;
426             }
427         }
428       else if (rc == 0)
429         break;
430       else
431         bytes_read += rc;
432     }
433       
434   buf[bytes_read] = '\0';
435
436   if (length)
437     *length = bytes_read;
438   
439   *contents = buf;
440
441   return TRUE;
442 }
443
444 static gboolean
445 get_contents_posix (const gchar *filename,
446                     gchar      **contents,
447                     gsize       *length,
448                     GError     **error)
449 {
450   struct stat stat_buf;
451   gint fd;
452   
453   /* O_BINARY useful on Cygwin */
454   fd = open (filename, O_RDONLY|O_BINARY);
455
456   if (fd < 0)
457     {
458       g_set_error (error,
459                    G_FILE_ERROR,
460                    g_file_error_from_errno (errno),
461                    _("Failed to open file '%s': %s"),
462                    filename, strerror (errno));
463
464       return FALSE;
465     }
466
467   /* I don't think this will ever fail, aside from ENOMEM, but. */
468   if (fstat (fd, &stat_buf) < 0)
469     {
470       close (fd);
471       
472       g_set_error (error,
473                    G_FILE_ERROR,
474                    g_file_error_from_errno (errno),
475                    _("Failed to get attributes of file '%s': fstat() failed: %s"),
476                    filename, strerror (errno));
477
478       return FALSE;
479     }
480
481   if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
482     {
483       return get_contents_regfile (filename,
484                                    &stat_buf,
485                                    fd,
486                                    contents,
487                                    length,
488                                    error);
489     }
490   else
491     {
492       FILE *f;
493
494       f = fdopen (fd, "r");
495       
496       if (f == NULL)
497         {
498           g_set_error (error,
499                        G_FILE_ERROR,
500                        g_file_error_from_errno (errno),
501                        _("Failed to open file '%s': fdopen() failed: %s"),
502                        filename, strerror (errno));
503           
504           return FALSE;
505         }
506   
507       return get_contents_stdio (filename, f, contents, length, error);
508     }
509 }
510
511 #else  /* G_OS_WIN32 */
512
513 static gboolean
514 get_contents_win32 (const gchar *filename,
515                     gchar      **contents,
516                     gsize       *length,
517                     GError     **error)
518 {
519   FILE *f;
520
521   /* I guess you want binary mode; maybe you want text sometimes? */
522   f = fopen (filename, "rb");
523
524   if (f == NULL)
525     {
526       g_set_error (error,
527                    G_FILE_ERROR,
528                    g_file_error_from_errno (errno),
529                    _("Failed to open file '%s': %s"),
530                    filename, strerror (errno));
531       
532       return FALSE;
533     }
534   
535   return get_contents_stdio (filename, f, contents, length, error);
536 }
537
538 #endif
539
540 /**
541  * g_file_get_contents:
542  * @filename: a file to read contents from
543  * @contents: location to store an allocated string
544  * @length: location to store length in bytes of the contents
545  * @error: return location for a #GError
546  * 
547  * Reads an entire file into allocated memory, with good error
548  * checking. If @error is set, %FALSE is returned, and @contents is set
549  * to %NULL. If %TRUE is returned, @error will not be set, and @contents
550  * will be set to the file contents.  The string stored in @contents
551  * will be nul-terminated, so for text files you can pass %NULL for the
552  * @length argument.  The error domain is #G_FILE_ERROR. Possible
553  * error codes are those in the #GFileError enumeration.
554  *
555  * Return value: %TRUE on success, %FALSE if error is set
556  **/
557 gboolean
558 g_file_get_contents (const gchar *filename,
559                      gchar      **contents,
560                      gsize       *length,
561                      GError     **error)
562 {  
563   g_return_val_if_fail (filename != NULL, FALSE);
564   g_return_val_if_fail (contents != NULL, FALSE);
565
566   *contents = NULL;
567   if (length)
568     *length = 0;
569
570 #ifdef G_OS_WIN32
571   return get_contents_win32 (filename, contents, length, error);
572 #else
573   return get_contents_posix (filename, contents, length, error);
574 #endif
575 }
576
577 /*
578  * mkstemp() implementation is from the GNU C library.
579  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
580  */
581 /**
582  * g_mkstemp:
583  * @tmpl: template filename
584  *
585  * Opens a temporary file. See the <function>mkstemp()</function> documentation
586  * on most UNIX-like systems. This is a portability wrapper, which simply calls 
587  * <function>mkstemp()</function> on systems that have it, and implements 
588  * it in GLib otherwise.
589  *
590  * The parameter is a string that should match the rules for
591  * <function>mkstemp()</function>, i.e. end in "XXXXXX". The X string will 
592  * be modified to form the name of a file that didn't exist.
593  *
594  * Return value: A file handle (as from <function>open()</function>) to the file
595  * opened for reading and writing. The file is opened in binary mode
596  * on platforms where there is a difference. The file handle should be
597  * closed with <function>close()</function>. In case of errors, -1 is returned.
598  */
599 int
600 g_mkstemp (char *tmpl)
601 {
602 #ifdef HAVE_MKSTEMP
603   return mkstemp (tmpl);
604 #else
605   int len;
606   char *XXXXXX;
607   int count, fd;
608   static const char letters[] =
609     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
610   static const int NLETTERS = sizeof (letters) - 1;
611   glong value;
612   GTimeVal tv;
613   static int counter = 0;
614
615   len = strlen (tmpl);
616   if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
617     return -1;
618
619   /* This is where the Xs start.  */
620   XXXXXX = &tmpl[len - 6];
621
622   /* Get some more or less random data.  */
623   g_get_current_time (&tv);
624   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
625
626   for (count = 0; count < 100; value += 7777, ++count)
627     {
628       glong v = value;
629
630       /* Fill in the random bits.  */
631       XXXXXX[0] = letters[v % NLETTERS];
632       v /= NLETTERS;
633       XXXXXX[1] = letters[v % NLETTERS];
634       v /= NLETTERS;
635       XXXXXX[2] = letters[v % NLETTERS];
636       v /= NLETTERS;
637       XXXXXX[3] = letters[v % NLETTERS];
638       v /= NLETTERS;
639       XXXXXX[4] = letters[v % NLETTERS];
640       v /= NLETTERS;
641       XXXXXX[5] = letters[v % NLETTERS];
642
643       fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
644
645       if (fd >= 0)
646         return fd;
647       else if (errno != EEXIST)
648         /* Any other error will apply also to other names we might
649          *  try, and there are 2^32 or so of them, so give up now.
650          */
651         return -1;
652     }
653
654   /* We got out of the loop because we ran out of combinations to try.  */
655   return -1;
656 #endif
657 }
658
659 /**
660  * g_file_open_tmp:
661  * @tmpl: Template for file name, as in g_mkstemp(), basename only
662  * @name_used: location to store actual name used
663  * @error: return location for a #GError
664  *
665  * Opens a file for writing in the preferred directory for temporary
666  * files (as returned by g_get_tmp_dir()). 
667  *
668  * @tmpl should be a string ending with six 'X' characters, as the
669  * parameter to g_mkstemp() (or <function>mkstemp()</function>). 
670  * However, unlike these functions, the template should only be a 
671  * basename, no directory components are allowed. If template is %NULL, 
672  * a default template is used.
673  *
674  * Note that in contrast to g_mkstemp() (and <function>mkstemp()</function>) 
675  * @tmpl is not modified, and might thus be a read-only literal string.
676  *
677  * The actual name used is returned in @name_used if non-%NULL. This
678  * string should be freed with g_free() when not needed any longer.
679  *
680  * Return value: A file handle (as from <function>open()</function>) to 
681  * the file opened for reading and writing. The file is opened in binary 
682  * mode on platforms where there is a difference. The file handle should be
683  * closed with <function>close()</function>. In case of errors, -1 is returned 
684  * and @error will be set.
685  **/
686 int
687 g_file_open_tmp (const char *tmpl,
688                  char      **name_used,
689                  GError    **error)
690 {
691   int retval;
692   const char *tmpdir;
693   char *sep;
694   char *fulltemplate;
695
696   if (tmpl == NULL)
697     tmpl = ".XXXXXX";
698
699   if (strchr (tmpl, G_DIR_SEPARATOR)
700 #ifdef G_OS_WIN32
701       || strchr (tmpl, '/')
702 #endif
703                                     )
704     {
705       g_set_error (error,
706                    G_FILE_ERROR,
707                    G_FILE_ERROR_FAILED,
708                    _("Template '%s' invalid, should not contain a '%s'"),
709                    tmpl, G_DIR_SEPARATOR_S);
710
711       return -1;
712     }
713   
714   if (strlen (tmpl) < 6 ||
715       strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
716     {
717       g_set_error (error,
718                    G_FILE_ERROR,
719                    G_FILE_ERROR_FAILED,
720                    _("Template '%s' doesn't end with XXXXXX"),
721                    tmpl);
722       return -1;
723     }
724
725   tmpdir = g_get_tmp_dir ();
726
727   if (tmpdir [strlen (tmpdir) - 1] == G_DIR_SEPARATOR)
728     sep = "";
729   else
730     sep = G_DIR_SEPARATOR_S;
731
732   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
733
734   retval = g_mkstemp (fulltemplate);
735
736   if (retval == -1)
737     {
738       g_set_error (error,
739                    G_FILE_ERROR,
740                    g_file_error_from_errno (errno),
741                    _("Failed to create file '%s': %s"),
742                    fulltemplate, strerror (errno));
743       g_free (fulltemplate);
744       return -1;
745     }
746
747   if (name_used)
748     *name_used = fulltemplate;
749   else
750     g_free (fulltemplate);
751
752   return retval;
753 }
754
755 static gchar *
756 g_build_pathv (const gchar *separator,
757                const gchar *first_element,
758                va_list      args)
759 {
760   GString *result;
761   gint separator_len = strlen (separator);
762   gboolean is_first = TRUE;
763   const gchar *next_element;
764
765   result = g_string_new (NULL);
766
767   next_element = first_element;
768
769   while (TRUE)
770     {
771       const gchar *element;
772       const gchar *start;
773       const gchar *end;
774
775       if (next_element)
776         {
777           element = next_element;
778           next_element = va_arg (args, gchar *);
779         }
780       else
781         break;
782
783       start = element;
784       
785       if (is_first)
786         is_first = FALSE;
787       else if (separator_len)
788         {
789           while (start &&
790                  strncmp (start, separator, separator_len) == 0)
791             start += separator_len;
792         }
793
794       end = start + strlen (start);
795       
796       if (next_element && separator_len)
797         {
798           while (end > start + separator_len &&
799                  strncmp (end - separator_len, separator, separator_len) == 0)
800             end -= separator_len;
801         }
802
803       if (end > start)
804         {
805           if (result->len > 0)
806             g_string_append (result, separator);
807
808           g_string_append_len (result, start, end - start);
809         }
810     }
811   
812   return g_string_free (result, FALSE);
813 }
814
815 /**
816  * g_build_path:
817  * @separator: a string used to separator the elements of the path.
818  * @first_element: the first element in the path
819  * @Varargs: remaining elements in path
820  * 
821  * Creates a path from a series of elements using @separator as the
822  * separator between elements. At the boundary between two elements,
823  * any trailing occurrences of separator in the first element, or
824  * leading occurrences of separator in the second element are removed
825  * and exactly one copy of the separator is inserted.
826  * 
827  * Return value: a newly-allocated string that must be freed with g_free().
828  **/
829 gchar *
830 g_build_path (const gchar *separator,
831               const gchar *first_element,
832               ...)
833 {
834   gchar *str;
835   va_list args;
836
837   g_return_val_if_fail (separator != NULL, NULL);
838
839   va_start (args, first_element);
840   str = g_build_pathv (separator, first_element, args);
841   va_end (args);
842
843   return str;
844 }
845
846 /**
847  * g_build_filename:
848  * @first_element: the first element in the path
849  * @Varargs: remaining elements in path
850  * 
851  * Creates a filename from a series of elements using the correct
852  * separator for filenames. This function behaves identically
853  * to <literal>g_build_path (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
854  *
855  * No attempt is made to force the resulting filename to be an absolute
856  * path. If the first element is a relative path, the result will
857  * be a relative path. 
858  * 
859  * Return value: a newly-allocated string that must be freed with g_free().
860  **/
861 gchar *
862 g_build_filename (const gchar *first_element, 
863                   ...)
864 {
865   gchar *str;
866   va_list args;
867
868   va_start (args, first_element);
869   str = g_build_pathv (G_DIR_SEPARATOR_S, first_element, args);
870   va_end (args);
871
872   return str;
873 }