Add gqsort.
[platform/upstream/glib.git] / 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 <string.h>
31 #include <errno.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <fcntl.h>
35 #include <stdlib.h>
36
37 #ifdef G_OS_WIN32
38 #include <io.h>
39 #ifndef F_OK
40 #define F_OK 0
41 #define X_OK 1
42 #define W_OK 2
43 #define R_OK 4
44 #endif /* !F_OK */
45
46 #ifndef S_ISREG
47 #define S_ISREG(mode) ((mode)&_S_IFREG)
48 #endif
49
50 #ifndef S_ISDIR
51 #define S_ISDIR(mode) ((mode)&_S_IFDIR)
52 #endif
53
54 #endif /* G_OS_WIN32 */
55
56 #ifndef S_ISLNK
57 #define S_ISLNK(x) 0
58 #endif
59
60 #ifndef O_BINARY
61 #define O_BINARY 0
62 #endif
63
64 #define _(x) x
65
66 /**
67  * g_file_test:
68  * @filename: a filename to test
69  * @test: bitfield of #GFileTest flags
70  * 
71  * Returns TRUE if any of the tests in the bitfield @test are
72  * TRUE. For example, (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)
73  * will return TRUE if the file exists; the check whether it's
74  * a directory doesn't matter since the existence test is TRUE.
75  * With the current set of available tests, there's no point
76  * passing in more than one test at a time.
77  *
78  * Return value: whether a test was TRUE
79  **/
80 gboolean
81 g_file_test (const gchar *filename,
82              GFileTest    test)
83 {
84   if (test & G_FILE_TEST_EXISTS)
85     return (access (filename, F_OK) == 0);
86   else if (test & G_FILE_TEST_IS_EXECUTABLE)
87     return (access (filename, X_OK) == 0);
88   else
89     {
90       struct stat s;
91       
92       if (stat (filename, &s) < 0)
93         return FALSE;
94
95       if ((test & G_FILE_TEST_IS_REGULAR) &&
96           S_ISREG (s.st_mode))
97         return TRUE;
98       else if ((test & G_FILE_TEST_IS_DIR) &&
99                S_ISDIR (s.st_mode))
100         return TRUE;
101       else if ((test & G_FILE_TEST_IS_SYMLINK) &&
102                S_ISLNK (s.st_mode))
103         return TRUE;
104       else
105         return FALSE;
106     }
107 }
108
109 GQuark
110 g_file_error_quark (void)
111 {
112   static GQuark q = 0;
113   if (q == 0)
114     q = g_quark_from_static_string ("g-file-error-quark");
115
116   return q;
117 }
118
119 GFileError
120 g_file_error_from_errno (gint en)
121 {
122   switch (en)
123     {
124 #ifdef EEXIST
125     case EEXIST:
126       return G_FILE_ERROR_EXIST;
127       break;
128 #endif
129
130 #ifdef EISDIR
131     case EISDIR:
132       return G_FILE_ERROR_ISDIR;
133       break;
134 #endif
135
136 #ifdef EACCES
137     case EACCES:
138       return G_FILE_ERROR_ACCES;
139       break;
140 #endif
141
142 #ifdef ENAMETOOLONG
143     case ENAMETOOLONG:
144       return G_FILE_ERROR_NAMETOOLONG;
145       break;
146 #endif
147
148 #ifdef ENOENT
149     case ENOENT:
150       return G_FILE_ERROR_NOENT;
151       break;
152 #endif
153
154 #ifdef ENOTDIR
155     case ENOTDIR:
156       return G_FILE_ERROR_NOTDIR;
157       break;
158 #endif
159
160 #ifdef ENXIO
161     case ENXIO:
162       return G_FILE_ERROR_NXIO;
163       break;
164 #endif
165
166 #ifdef ENODEV
167     case ENODEV:
168       return G_FILE_ERROR_NODEV;
169       break;
170 #endif
171
172 #ifdef EROFS
173     case EROFS:
174       return G_FILE_ERROR_ROFS;
175       break;
176 #endif
177
178 #ifdef ETXTBSY
179     case ETXTBSY:
180       return G_FILE_ERROR_TXTBSY;
181       break;
182 #endif
183
184 #ifdef EFAULT
185     case EFAULT:
186       return G_FILE_ERROR_FAULT;
187       break;
188 #endif
189
190 #ifdef ELOOP
191     case ELOOP:
192       return G_FILE_ERROR_LOOP;
193       break;
194 #endif
195
196 #ifdef ENOSPC
197     case ENOSPC:
198       return G_FILE_ERROR_NOSPC;
199       break;
200 #endif
201
202 #ifdef ENOMEM
203     case ENOMEM:
204       return G_FILE_ERROR_NOMEM;
205       break;
206 #endif
207
208 #ifdef EMFILE
209     case EMFILE:
210       return G_FILE_ERROR_MFILE;
211       break;
212 #endif
213
214 #ifdef ENFILE
215     case ENFILE:
216       return G_FILE_ERROR_NFILE;
217       break;
218 #endif
219
220 #ifdef EBADF
221     case EBADF:
222       return G_FILE_ERROR_BADF;
223       break;
224 #endif
225
226 #ifdef EINVAL
227     case EINVAL:
228       return G_FILE_ERROR_INVAL;
229       break;
230 #endif
231
232 #ifdef EPIPE
233     case EPIPE:
234       return G_FILE_ERROR_PIPE;
235       break;
236 #endif
237
238 #ifdef EAGAIN
239     case EAGAIN:
240       return G_FILE_ERROR_AGAIN;
241       break;
242 #endif
243
244 #ifdef EINTR
245     case EINTR:
246       return G_FILE_ERROR_INTR;
247       break;
248 #endif
249
250 #ifdef EIO
251     case EIO:
252       return G_FILE_ERROR_IO;
253       break;
254 #endif
255
256 #ifdef EPERM
257     case EPERM:
258       return G_FILE_ERROR_PERM;
259       break;
260 #endif
261       
262     default:
263       return G_FILE_ERROR_FAILED;
264       break;
265     }
266 }
267
268 static gboolean
269 get_contents_stdio (const gchar *filename,
270                     FILE        *f,
271                     gchar      **contents,
272                     guint       *length,
273                     GError     **error)
274 {
275   gchar buf[2048];
276   size_t bytes;
277   GString *str;
278
279   g_assert (f != NULL);
280   
281   str = g_string_new ("");
282   
283   while (!feof (f))
284     {
285       bytes = fread (buf, 1, 2048, f);
286       
287       if (ferror (f))
288         {
289           g_set_error (error,
290                        G_FILE_ERROR,
291                        g_file_error_from_errno (errno),
292                        _("Error reading file '%s': %s"),
293                        filename, strerror (errno));
294
295           g_string_free (str, TRUE);
296           
297           return FALSE;
298         }
299
300       g_string_append_len (str, buf, bytes);
301     }
302
303   fclose (f);
304
305   if (length)
306     *length = str->len;
307   
308   *contents = g_string_free (str, FALSE);
309
310   return TRUE;  
311 }
312
313 #ifndef G_OS_WIN32
314
315 static gboolean
316 get_contents_regfile (const gchar *filename,
317                       struct stat *stat_buf,
318                       gint         fd,
319                       gchar      **contents,
320                       guint       *length,
321                       GError     **error)
322 {
323   gchar *buf;
324   size_t bytes_read;
325   size_t size;
326       
327   size = stat_buf->st_size;
328
329   buf = g_new (gchar, size + 1);
330       
331   bytes_read = 0;
332   while (bytes_read < size)
333     {
334       gint rc;
335           
336       rc = read (fd, buf + bytes_read, size - bytes_read);
337
338       if (rc < 0)
339         {
340           if (errno != EINTR) 
341             {
342               close (fd);
343
344               g_free (buf);
345                   
346               g_set_error (error,
347                            G_FILE_ERROR,
348                            g_file_error_from_errno (errno),
349                            _("Failed to read from file '%s': %s"),
350                            filename, strerror (errno));
351
352               return FALSE;
353             }
354         }
355       else if (rc == 0)
356         break;
357       else
358         bytes_read += rc;
359     }
360       
361   buf[bytes_read] = '\0';
362
363   if (length)
364     *length = bytes_read;
365   
366   *contents = buf;
367
368   return TRUE;
369 }
370
371 static gboolean
372 get_contents_posix (const gchar *filename,
373                     gchar      **contents,
374                     guint       *length,
375                     GError     **error)
376 {
377   struct stat stat_buf;
378   gint fd;
379   
380   fd = open (filename, O_RDONLY);
381
382   if (fd < 0)
383     {
384       g_set_error (error,
385                    G_FILE_ERROR,
386                    g_file_error_from_errno (errno),
387                    _("Failed to open file '%s': %s"),
388                    filename, strerror (errno));
389
390       return FALSE;
391     }
392
393   /* I don't think this will ever fail, aside from ENOMEM, but. */
394   if (fstat (fd, &stat_buf) < 0)
395     {
396       close (fd);
397       
398       g_set_error (error,
399                    G_FILE_ERROR,
400                    g_file_error_from_errno (errno),
401                    _("Failed to get attributes of file '%s': fstat() failed: %s"),
402                    filename, strerror (errno));
403
404       return FALSE;
405     }
406
407   if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
408     {
409       return get_contents_regfile (filename,
410                                    &stat_buf,
411                                    fd,
412                                    contents,
413                                    length,
414                                    error);
415     }
416   else
417     {
418       FILE *f;
419
420       f = fdopen (fd, "r");
421       
422       if (f == NULL)
423         {
424           g_set_error (error,
425                        G_FILE_ERROR,
426                        g_file_error_from_errno (errno),
427                        _("Failed to open file '%s': fdopen() failed: %s"),
428                        filename, strerror (errno));
429           
430           return FALSE;
431         }
432   
433       return get_contents_stdio (filename, f, contents, length, error);
434     }
435 }
436
437 #else  /* G_OS_WIN32 */
438
439 static gboolean
440 get_contents_win32 (const gchar *filename,
441                     gchar      **contents,
442                     guint       *length,
443                     GError     **error)
444 {
445   FILE *f;
446
447   /* I guess you want binary mode; maybe you want text sometimes? */
448   f = fopen (filename, "rb");
449
450   if (f == NULL)
451     {
452       g_set_error (error,
453                    G_FILE_ERROR,
454                    g_file_error_from_errno (errno),
455                    _("Failed to open file '%s': %s"),
456                    filename, strerror (errno));
457       
458       return FALSE;
459     }
460   
461   return get_contents_stdio (filename, f, contents, length, error);
462 }
463
464 #endif
465
466 /**
467  * g_file_get_contents:
468  * @filename: a file to read contents from
469  * @contents: location to store an allocated string
470  * @length: location to store length in bytes of the contents
471  * @error: return location for a #GError
472  * 
473  * Reads an entire file into allocated memory, with good error
474  * checking. If @error is set, FALSE is returned, and @contents is set
475  * to NULL. If TRUE is returned, @error will not be set, and @contents
476  * will be set to the file contents.  The string stored in @contents
477  * will be nul-terminated, so for text files you can pass NULL for the
478  * @length argument.  The error domain is #G_FILE_ERROR. Possible
479  * error codes are those in the #GFileError enumeration.
480  *
481  * FIXME currently crashes if the file is too big to fit in memory;
482  * should probably use g_try_malloc() when we have that function.
483  * 
484  * Return value: TRUE on success, FALSE if error is set
485  **/
486 gboolean
487 g_file_get_contents (const gchar *filename,
488                      gchar      **contents,
489                      guint       *length,
490                      GError     **error)
491 {  
492   g_return_val_if_fail (filename != NULL, FALSE);
493   g_return_val_if_fail (contents != NULL, FALSE);
494
495   *contents = NULL;
496   if (length)
497     *length = 0;
498
499 #ifdef G_OS_WIN32
500   return get_contents_win32 (filename, contents, length, error);
501 #else
502   return get_contents_posix (filename, contents, length, error);
503 #endif
504 }
505
506 /*
507  * mkstemp() implementation is from the GNU C library.
508  * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
509  */
510 /**
511  * g_mkstemp:
512  * @tmpl: template filename
513  *
514  * Open a temporary file. See "man mkstemp" on most UNIX-like systems.
515  * This is a portability wrapper, which simply calls mkstemp() on systems
516  * that have it, and implements it in GLib otherwise.
517  *
518  * The parameter is a string that should match the rules for mktemp, i.e.
519  * end in "XXXXXX". The X string will be modified to form the name
520  * of a file that didn't exist.
521  *
522  * Return value: A file handle (as from open()) to the file
523  * opened for reading and writing. The file is opened in binary mode
524  * on platforms where there is a difference. The file handle should be
525  * closed with close(). In case of errors, -1 is returned.
526  */
527 int
528 g_mkstemp (char *tmpl)
529 {
530 #ifdef HAVE_MKSTEMP
531   return mkstemp (tmpl);
532 #else
533   int len;
534   char *XXXXXX;
535   int count, fd;
536   static const char letters[] =
537     "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
538   static const int NLETTERS = sizeof (letters) - 1;
539   glong value;
540   GTimeVal tv;
541   static int counter = 0;
542
543   len = strlen (tmpl);
544   if (len < 6 || strcmp (&tmpl[len - 6], "XXXXXX"))
545     return -1;
546
547   /* This is where the Xs start.  */
548   XXXXXX = &tmpl[len - 6];
549
550   /* Get some more or less random data.  */
551   g_get_current_time (&tv);
552   value = (tv.tv_usec ^ tv.tv_sec) + counter++;
553
554   for (count = 0; count < 100; value += 7777, ++count)
555     {
556       glong v = value;
557
558       /* Fill in the random bits.  */
559       XXXXXX[0] = letters[v % NLETTERS];
560       v /= NLETTERS;
561       XXXXXX[1] = letters[v % NLETTERS];
562       v /= NLETTERS;
563       XXXXXX[2] = letters[v % NLETTERS];
564       v /= NLETTERS;
565       XXXXXX[3] = letters[v % NLETTERS];
566       v /= NLETTERS;
567       XXXXXX[4] = letters[v % NLETTERS];
568       v /= NLETTERS;
569       XXXXXX[5] = letters[v % NLETTERS];
570
571       fd = open (tmpl, O_RDWR | O_CREAT | O_EXCL | O_BINARY, 0600);
572
573       if (fd >= 0)
574         return fd;
575       else if (errno != EEXIST)
576         /* Any other error will apply also to other names we might
577          *  try, and there are 2^32 or so of them, so give up now.
578          */
579         return -1;
580     }
581
582   /* We got out of the loop because we ran out of combinations to try.  */
583   return -1;
584 #endif
585 }
586
587 /**
588  * g_file_open_tmp:
589  * @tmpl: Template for file name, as in g_mkstemp, basename only
590  * @name_used: location to store actual name used
591  * @error: return location for a #GError
592  *
593  * Opens a file for writing in the preferred directory for temporary
594  * files (as returned by g_get_tmp_dir()). 
595  *
596  * @tmpl should be a string ending with six 'X' characters, as the
597  * parameter to g_mkstemp() (or mkstemp()). However, unlike these
598  * functions, the template should only be a basename, no directory
599  * components are allowed. If template is NULL, a default template is
600  * used.
601  *
602  * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
603  * modified, and might thus be a read-only literal string.
604  *
605  * The actual name used is returned in @name_used if non-NULL. This
606  * string should be freed with g_free when not needed any longer.
607  *
608  * Return value: A file handle (as from open()) to the file
609  * opened for reading and writing. The file is opened in binary mode
610  * on platforms where there is a difference. The file handle should be
611  * closed with close(). In case of errors, -1 is returned and
612  * @error will be set.
613  **/
614 int
615 g_file_open_tmp (const char *tmpl,
616                  char      **name_used,
617                  GError    **error)
618 {
619   int retval;
620   char *tmpdir;
621   char *sep;
622   char *fulltemplate;
623
624   if (tmpl == NULL)
625     tmpl = ".XXXXXX";
626
627   if (strchr (tmpl, G_DIR_SEPARATOR))
628     {
629       g_set_error (error,
630                    G_FILE_ERROR,
631                    G_FILE_ERROR_FAILED,
632                    _("Template '%s' illegal, should not contain a '%s'"),
633                    tmpl, G_DIR_SEPARATOR_S);
634
635       return -1;
636     }
637   
638   if (strlen (tmpl) < 6 ||
639       strcmp (tmpl + strlen (tmpl) - 6, "XXXXXX") != 0)
640     {
641       g_set_error (error,
642                    G_FILE_ERROR,
643                    G_FILE_ERROR_FAILED,
644                    _("Template '%s' doesn end with XXXXXX"),
645                    tmpl);
646       return -1;
647     }
648
649   tmpdir = g_get_tmp_dir ();
650
651   if (tmpdir [strlen (tmpdir) - 1] == G_DIR_SEPARATOR)
652     sep = "";
653   else
654     sep = G_DIR_SEPARATOR_S;
655
656   fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
657
658   retval = g_mkstemp (fulltemplate);
659
660   if (retval == -1)
661     {
662       g_set_error (error,
663                    G_FILE_ERROR,
664                    g_file_error_from_errno (errno),
665                    _("Failed to create file '%s': %s"),
666                    fulltemplate, strerror (errno));
667       g_free (fulltemplate);
668       return -1;
669     }
670
671   if (name_used)
672     *name_used = fulltemplate;
673   else
674     g_free (fulltemplate);
675
676   return retval;
677 }