~noskcaj/ubuntu/trusty/cogl/1.16.2

« back to all changes in this revision

Viewing changes to deps/glib/gfileutils.c

  • Committer: Package Import Robot
  • Author(s): Jeremy Bicha, Jeremy Bicha, Rico Tzschichholz
  • Date: 2013-02-26 16:43:25 UTC
  • mfrom: (1.1.10)
  • Revision ID: package-import@ubuntu.com-20130226164325-t4z9rylpa20v0p6q
Tags: 1.13.4-0ubuntu1
[ Jeremy Bicha ]
* New upstream release
  - soname bump
* debian/control.in:
  - Bump minimum glib to 2.32
  - Drop obsolete breaks/replaces
  - Bump libclutter-1.0-dev breaks for soname transition
* debian/libcogl-dev.install:
  - Add some missing files

[ Rico Tzschichholz ]
* debian/control.in:
  - Build-depend on libxrandr-dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
#include "gconvert.h"
 
56
#include "gmain.h"
 
57
 
 
58
#ifdef HAVE_LINUX_MAGIC_H /* for btrfs check */
 
59
#include <linux/magic.h>
 
60
#include <sys/vfs.h>
 
61
#endif
 
62
 
 
63
/**
 
64
 * g_mkdir_with_parents:
 
65
 * @pathname: a pathname in the GLib file name encoding
 
66
 * @mode: permissions to use for newly created directories
 
67
 *
 
68
 * Create a directory if it doesn't already exist. Create intermediate
 
69
 * parent directories as needed, too.
 
70
 *
 
71
 * Returns: 0 if the directory already exists, or was successfully
 
72
 * created. Returns -1 if an error occurred, with errno set.
 
73
 *
 
74
 * Since: 2.8
 
75
 */
 
76
int
 
77
g_mkdir_with_parents (const gchar *pathname,
 
78
                      int          mode)
 
79
{
 
80
  gchar *fn, *p;
 
81
 
 
82
  if (pathname == NULL || *pathname == '\0')
 
83
    {
 
84
      errno = EINVAL;
 
85
      return -1;
 
86
    }
 
87
 
 
88
  fn = g_strdup (pathname);
 
89
 
 
90
  if (g_path_is_absolute (fn))
 
91
    p = (gchar *) g_path_skip_root (fn);
 
92
  else
 
93
    p = fn;
 
94
 
 
95
  do
 
96
    {
 
97
      while (*p && !G_IS_DIR_SEPARATOR (*p))
 
98
        p++;
 
99
      
 
100
      if (!*p)
 
101
        p = NULL;
 
102
      else
 
103
        *p = '\0';
 
104
      
 
105
      if (!g_file_test (fn, G_FILE_TEST_EXISTS))
 
106
        {
 
107
          if (g_mkdir (fn, mode) == -1 && errno != EEXIST)
 
108
            {
 
109
              int errno_save = errno;
 
110
              g_free (fn);
 
111
              errno = errno_save;
 
112
              return -1;
 
113
            }
 
114
        }
 
115
      else if (!g_file_test (fn, G_FILE_TEST_IS_DIR))
 
116
        {
 
117
          g_free (fn);
 
118
          errno = ENOTDIR;
 
119
          return -1;
 
120
        }
 
121
      if (p)
 
122
        {
 
123
          *p++ = G_DIR_SEPARATOR;
 
124
          while (*p && G_IS_DIR_SEPARATOR (*p))
 
125
            p++;
 
126
        }
 
127
    }
 
128
  while (p);
 
129
 
 
130
  g_free (fn);
 
131
 
 
132
  return 0;
 
133
}
 
134
 
 
135
/**
 
136
 * g_file_test:
 
137
 * @filename: a filename to test in the GLib file name encoding
 
138
 * @test: bitfield of #GFileTest flags
 
139
 * 
 
140
 * Returns %TRUE if any of the tests in the bitfield @test are
 
141
 * %TRUE. For example, <literal>(G_FILE_TEST_EXISTS | 
 
142
 * G_FILE_TEST_IS_DIR)</literal> will return %TRUE if the file exists; 
 
143
 * the check whether it's a directory doesn't matter since the existence 
 
144
 * test is %TRUE. With the current set of available tests, there's no point
 
145
 * passing in more than one test at a time.
 
146
 * 
 
147
 * Apart from %G_FILE_TEST_IS_SYMLINK all tests follow symbolic links,
 
148
 * so for a symbolic link to a regular file g_file_test() will return
 
149
 * %TRUE for both %G_FILE_TEST_IS_SYMLINK and %G_FILE_TEST_IS_REGULAR.
 
150
 *
 
151
 * Note, that for a dangling symbolic link g_file_test() will return
 
152
 * %TRUE for %G_FILE_TEST_IS_SYMLINK and %FALSE for all other flags.
 
153
 *
 
154
 * You should never use g_file_test() to test whether it is safe
 
155
 * to perform an operation, because there is always the possibility
 
156
 * of the condition changing before you actually perform the operation.
 
157
 * For example, you might think you could use %G_FILE_TEST_IS_SYMLINK
 
158
 * to know whether it is safe to write to a file without being
 
159
 * tricked into writing into a different location. It doesn't work!
 
160
 * |[
 
161
 * /&ast; DON'T DO THIS &ast;/
 
162
 *  if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK)) 
 
163
 *    {
 
164
 *      fd = g_open (filename, O_WRONLY);
 
165
 *      /&ast; write to fd &ast;/
 
166
 *    }
 
167
 * ]|
 
168
 *
 
169
 * Another thing to note is that %G_FILE_TEST_EXISTS and
 
170
 * %G_FILE_TEST_IS_EXECUTABLE are implemented using the access()
 
171
 * system call. This usually doesn't matter, but if your program
 
172
 * is setuid or setgid it means that these tests will give you
 
173
 * the answer for the real user ID and group ID, rather than the
 
174
 * effective user ID and group ID.
 
175
 *
 
176
 * On Windows, there are no symlinks, so testing for
 
177
 * %G_FILE_TEST_IS_SYMLINK will always return %FALSE. Testing for
 
178
 * %G_FILE_TEST_IS_EXECUTABLE will just check that the file exists and
 
179
 * its name indicates that it is executable, checking for well-known
 
180
 * extensions and those listed in the %PATHEXT environment variable.
 
181
 *
 
182
 * Return value: whether a test was %TRUE
 
183
 **/
 
184
gboolean
 
185
g_file_test (const gchar *filename,
 
186
             GFileTest    test)
 
187
{
 
188
#ifdef G_OS_WIN32
 
189
/* stuff missing in std vc6 api */
 
190
#  ifndef INVALID_FILE_ATTRIBUTES
 
191
#    define INVALID_FILE_ATTRIBUTES -1
 
192
#  endif
 
193
#  ifndef FILE_ATTRIBUTE_DEVICE
 
194
#    define FILE_ATTRIBUTE_DEVICE 64
 
195
#  endif
 
196
  int attributes;
 
197
  wchar_t *wfilename = g_utf8_to_utf16 (filename, -1, NULL, NULL, NULL);
 
198
 
 
199
  if (wfilename == NULL)
 
200
    return FALSE;
 
201
 
 
202
  attributes = GetFileAttributesW (wfilename);
 
203
 
 
204
  g_free (wfilename);
 
205
 
 
206
  if (attributes == INVALID_FILE_ATTRIBUTES)
 
207
    return FALSE;
 
208
 
 
209
  if (test & G_FILE_TEST_EXISTS)
 
210
    return TRUE;
 
211
      
 
212
  if (test & G_FILE_TEST_IS_REGULAR)
 
213
    {
 
214
      if ((attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0)
 
215
        return TRUE;
 
216
    }
 
217
 
 
218
  if (test & G_FILE_TEST_IS_DIR)
 
219
    {
 
220
      if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
 
221
        return TRUE;
 
222
    }
 
223
 
 
224
  /* "while" so that we can exit this "loop" with a simple "break" */
 
225
  while (test & G_FILE_TEST_IS_EXECUTABLE)
 
226
    {
 
227
      const gchar *lastdot = strrchr (filename, '.');
 
228
      const gchar *pathext = NULL, *p;
 
229
      int extlen;
 
230
 
 
231
      if (lastdot == NULL)
 
232
        break;
 
233
 
 
234
      if (_stricmp (lastdot, ".exe") == 0 ||
 
235
          _stricmp (lastdot, ".cmd") == 0 ||
 
236
          _stricmp (lastdot, ".bat") == 0 ||
 
237
          _stricmp (lastdot, ".com") == 0)
 
238
        return TRUE;
 
239
 
 
240
      /* Check if it is one of the types listed in %PATHEXT% */
 
241
 
 
242
      pathext = g_getenv ("PATHEXT");
 
243
      if (pathext == NULL)
 
244
        break;
 
245
 
 
246
      pathext = g_utf8_casefold (pathext, -1);
 
247
 
 
248
      lastdot = g_utf8_casefold (lastdot, -1);
 
249
      extlen = strlen (lastdot);
 
250
 
 
251
      p = pathext;
 
252
      while (TRUE)
 
253
        {
 
254
          const gchar *q = strchr (p, ';');
 
255
          if (q == NULL)
 
256
            q = p + strlen (p);
 
257
          if (extlen == q - p &&
 
258
              memcmp (lastdot, p, extlen) == 0)
 
259
            {
 
260
              g_free ((gchar *) pathext);
 
261
              g_free ((gchar *) lastdot);
 
262
              return TRUE;
 
263
            }
 
264
          if (*q)
 
265
            p = q + 1;
 
266
          else
 
267
            break;
 
268
        }
 
269
 
 
270
      g_free ((gchar *) pathext);
 
271
      g_free ((gchar *) lastdot);
 
272
      break;
 
273
    }
 
274
 
 
275
  return FALSE;
 
276
#else
 
277
  if ((test & G_FILE_TEST_EXISTS) && (access (filename, F_OK) == 0))
 
278
    return TRUE;
 
279
  
 
280
  if ((test & G_FILE_TEST_IS_EXECUTABLE) && (access (filename, X_OK) == 0))
 
281
    {
 
282
      if (getuid () != 0)
 
283
        return TRUE;
 
284
 
 
285
      /* For root, on some POSIX systems, access (filename, X_OK)
 
286
       * will succeed even if no executable bits are set on the
 
287
       * file. We fall through to a stat test to avoid that.
 
288
       */
 
289
    }
 
290
  else
 
291
    test &= ~G_FILE_TEST_IS_EXECUTABLE;
 
292
 
 
293
  if (test & G_FILE_TEST_IS_SYMLINK)
 
294
    {
 
295
      struct stat s;
 
296
 
 
297
      if ((lstat (filename, &s) == 0) && S_ISLNK (s.st_mode))
 
298
        return TRUE;
 
299
    }
 
300
  
 
301
  if (test & (G_FILE_TEST_IS_REGULAR |
 
302
              G_FILE_TEST_IS_DIR |
 
303
              G_FILE_TEST_IS_EXECUTABLE))
 
304
    {
 
305
      struct stat s;
 
306
      
 
307
      if (stat (filename, &s) == 0)
 
308
        {
 
309
          if ((test & G_FILE_TEST_IS_REGULAR) && S_ISREG (s.st_mode))
 
310
            return TRUE;
 
311
          
 
312
          if ((test & G_FILE_TEST_IS_DIR) && S_ISDIR (s.st_mode))
 
313
            return TRUE;
 
314
 
 
315
          /* The extra test for root when access (file, X_OK) succeeds.
 
316
           */
 
317
          if ((test & G_FILE_TEST_IS_EXECUTABLE) &&
 
318
              ((s.st_mode & S_IXOTH) ||
 
319
               (s.st_mode & S_IXUSR) ||
 
320
               (s.st_mode & S_IXGRP)))
 
321
            return TRUE;
 
322
        }
 
323
    }
 
324
 
 
325
  return FALSE;
 
326
#endif
 
327
}
 
328
 
 
329
GQuark
 
330
g_file_error_quark (void)
 
331
{
 
332
  return g_quark_from_static_string ("g-file-error-quark");
 
333
}
 
334
 
 
335
/**
 
336
 * g_file_error_from_errno:
 
337
 * @err_no: an "errno" value
 
338
 * 
 
339
 * Gets a #GFileError constant based on the passed-in @errno.
 
340
 * For example, if you pass in %EEXIST this function returns
 
341
 * #G_FILE_ERROR_EXIST. Unlike @errno values, you can portably
 
342
 * assume that all #GFileError values will exist.
 
343
 *
 
344
 * Normally a #GFileError value goes into a #GError returned
 
345
 * from a function that manipulates files. So you would use
 
346
 * g_file_error_from_errno() when constructing a #GError.
 
347
 * 
 
348
 * Return value: #GFileError corresponding to the given @errno
 
349
 **/
 
350
GFileError
 
351
g_file_error_from_errno (gint err_no)
 
352
{
 
353
  switch (err_no)
 
354
    {
 
355
#ifdef EEXIST
 
356
    case EEXIST:
 
357
      return G_FILE_ERROR_EXIST;
 
358
      break;
 
359
#endif
 
360
 
 
361
#ifdef EISDIR
 
362
    case EISDIR:
 
363
      return G_FILE_ERROR_ISDIR;
 
364
      break;
 
365
#endif
 
366
 
 
367
#ifdef EACCES
 
368
    case EACCES:
 
369
      return G_FILE_ERROR_ACCES;
 
370
      break;
 
371
#endif
 
372
 
 
373
#ifdef ENAMETOOLONG
 
374
    case ENAMETOOLONG:
 
375
      return G_FILE_ERROR_NAMETOOLONG;
 
376
      break;
 
377
#endif
 
378
 
 
379
#ifdef ENOENT
 
380
    case ENOENT:
 
381
      return G_FILE_ERROR_NOENT;
 
382
      break;
 
383
#endif
 
384
 
 
385
#ifdef ENOTDIR
 
386
    case ENOTDIR:
 
387
      return G_FILE_ERROR_NOTDIR;
 
388
      break;
 
389
#endif
 
390
 
 
391
#ifdef ENXIO
 
392
    case ENXIO:
 
393
      return G_FILE_ERROR_NXIO;
 
394
      break;
 
395
#endif
 
396
 
 
397
#ifdef ENODEV
 
398
    case ENODEV:
 
399
      return G_FILE_ERROR_NODEV;
 
400
      break;
 
401
#endif
 
402
 
 
403
#ifdef EROFS
 
404
    case EROFS:
 
405
      return G_FILE_ERROR_ROFS;
 
406
      break;
 
407
#endif
 
408
 
 
409
#ifdef ETXTBSY
 
410
    case ETXTBSY:
 
411
      return G_FILE_ERROR_TXTBSY;
 
412
      break;
 
413
#endif
 
414
 
 
415
#ifdef EFAULT
 
416
    case EFAULT:
 
417
      return G_FILE_ERROR_FAULT;
 
418
      break;
 
419
#endif
 
420
 
 
421
#ifdef ELOOP
 
422
    case ELOOP:
 
423
      return G_FILE_ERROR_LOOP;
 
424
      break;
 
425
#endif
 
426
 
 
427
#ifdef ENOSPC
 
428
    case ENOSPC:
 
429
      return G_FILE_ERROR_NOSPC;
 
430
      break;
 
431
#endif
 
432
 
 
433
#ifdef ENOMEM
 
434
    case ENOMEM:
 
435
      return G_FILE_ERROR_NOMEM;
 
436
      break;
 
437
#endif
 
438
 
 
439
#ifdef EMFILE
 
440
    case EMFILE:
 
441
      return G_FILE_ERROR_MFILE;
 
442
      break;
 
443
#endif
 
444
 
 
445
#ifdef ENFILE
 
446
    case ENFILE:
 
447
      return G_FILE_ERROR_NFILE;
 
448
      break;
 
449
#endif
 
450
 
 
451
#ifdef EBADF
 
452
    case EBADF:
 
453
      return G_FILE_ERROR_BADF;
 
454
      break;
 
455
#endif
 
456
 
 
457
#ifdef EINVAL
 
458
    case EINVAL:
 
459
      return G_FILE_ERROR_INVAL;
 
460
      break;
 
461
#endif
 
462
 
 
463
#ifdef EPIPE
 
464
    case EPIPE:
 
465
      return G_FILE_ERROR_PIPE;
 
466
      break;
 
467
#endif
 
468
 
 
469
#ifdef EAGAIN
 
470
    case EAGAIN:
 
471
      return G_FILE_ERROR_AGAIN;
 
472
      break;
 
473
#endif
 
474
 
 
475
#ifdef EINTR
 
476
    case EINTR:
 
477
      return G_FILE_ERROR_INTR;
 
478
      break;
 
479
#endif
 
480
 
 
481
#ifdef EIO
 
482
    case EIO:
 
483
      return G_FILE_ERROR_IO;
 
484
      break;
 
485
#endif
 
486
 
 
487
#ifdef EPERM
 
488
    case EPERM:
 
489
      return G_FILE_ERROR_PERM;
 
490
      break;
 
491
#endif
 
492
 
 
493
#ifdef ENOSYS
 
494
    case ENOSYS:
 
495
      return G_FILE_ERROR_NOSYS;
 
496
      break;
 
497
#endif
 
498
 
 
499
    default:
 
500
      return G_FILE_ERROR_FAILED;
 
501
      break;
 
502
    }
 
503
}
 
504
 
 
505
static gboolean
 
506
get_contents_stdio (const gchar  *display_filename,
 
507
                    FILE         *f,
 
508
                    gchar       **contents,
 
509
                    gsize        *length,
 
510
                    GError      **error)
 
511
{
 
512
  gchar buf[4096];
 
513
  gsize bytes;
 
514
  gchar *str = NULL;
 
515
  gsize total_bytes = 0;
 
516
  gsize total_allocated = 0;
 
517
  gchar *tmp;
 
518
 
 
519
  g_assert (f != NULL);
 
520
 
 
521
  while (!feof (f))
 
522
    {
 
523
      gint save_errno;
 
524
 
 
525
      bytes = fread (buf, 1, sizeof (buf), f);
 
526
      save_errno = errno;
 
527
 
 
528
      while ((total_bytes + bytes + 1) > total_allocated)
 
529
        {
 
530
          if (str)
 
531
            total_allocated *= 2;
 
532
          else
 
533
            total_allocated = MIN (bytes + 1, sizeof (buf));
 
534
 
 
535
          tmp = g_try_realloc (str, total_allocated);
 
536
 
 
537
          if (tmp == NULL)
 
538
            {
 
539
              g_set_error (error,
 
540
                           G_FILE_ERROR,
 
541
                           G_FILE_ERROR_NOMEM,
 
542
                           _("Could not allocate %lu bytes to read file \"%s\""),
 
543
                           (gulong) total_allocated,
 
544
                           display_filename);
 
545
 
 
546
              goto error;
 
547
            }
 
548
 
 
549
          str = tmp;
 
550
        }
 
551
 
 
552
      if (ferror (f))
 
553
        {
 
554
          g_set_error (error,
 
555
                       G_FILE_ERROR,
 
556
                       g_file_error_from_errno (save_errno),
 
557
                       _("Error reading file '%s': %s"),
 
558
                       display_filename,
 
559
                       g_strerror (save_errno));
 
560
 
 
561
          goto error;
 
562
        }
 
563
 
 
564
      memcpy (str + total_bytes, buf, bytes);
 
565
 
 
566
      if (total_bytes + bytes < total_bytes) 
 
567
        {
 
568
          g_set_error (error,
 
569
                       G_FILE_ERROR,
 
570
                       G_FILE_ERROR_FAILED,
 
571
                       _("File \"%s\" is too large"),
 
572
                       display_filename);
 
573
 
 
574
          goto error;
 
575
        }
 
576
 
 
577
      total_bytes += bytes;
 
578
    }
 
579
 
 
580
  fclose (f);
 
581
 
 
582
  if (total_allocated == 0)
 
583
    {
 
584
      str = g_new (gchar, 1);
 
585
      total_bytes = 0;
 
586
    }
 
587
 
 
588
  str[total_bytes] = '\0';
 
589
 
 
590
  if (length)
 
591
    *length = total_bytes;
 
592
 
 
593
  *contents = str;
 
594
 
 
595
  return TRUE;
 
596
 
 
597
 error:
 
598
 
 
599
  g_free (str);
 
600
  fclose (f);
 
601
 
 
602
  return FALSE;
 
603
}
 
604
 
 
605
#ifndef G_OS_WIN32
 
606
 
 
607
static gboolean
 
608
get_contents_regfile (const gchar  *display_filename,
 
609
                      struct stat  *stat_buf,
 
610
                      gint          fd,
 
611
                      gchar       **contents,
 
612
                      gsize        *length,
 
613
                      GError      **error)
 
614
{
 
615
  gchar *buf;
 
616
  gsize bytes_read;
 
617
  gsize size;
 
618
  gsize alloc_size;
 
619
  
 
620
  size = stat_buf->st_size;
 
621
 
 
622
  alloc_size = size + 1;
 
623
  buf = g_try_malloc (alloc_size);
 
624
 
 
625
  if (buf == NULL)
 
626
    {
 
627
      g_set_error (error,
 
628
                   G_FILE_ERROR,
 
629
                   G_FILE_ERROR_NOMEM,
 
630
                   _("Could not allocate %lu bytes to read file \"%s\""),
 
631
                   (gulong) alloc_size, 
 
632
                   display_filename);
 
633
 
 
634
      goto error;
 
635
    }
 
636
  
 
637
  bytes_read = 0;
 
638
  while (bytes_read < size)
 
639
    {
 
640
      gssize rc;
 
641
          
 
642
      rc = read (fd, buf + bytes_read, size - bytes_read);
 
643
 
 
644
      if (rc < 0)
 
645
        {
 
646
          if (errno != EINTR) 
 
647
            {
 
648
              int save_errno = errno;
 
649
 
 
650
              g_free (buf);
 
651
              g_set_error (error,
 
652
                           G_FILE_ERROR,
 
653
                           g_file_error_from_errno (save_errno),
 
654
                           _("Failed to read from file '%s': %s"),
 
655
                           display_filename, 
 
656
                           g_strerror (save_errno));
 
657
 
 
658
              goto error;
 
659
            }
 
660
        }
 
661
      else if (rc == 0)
 
662
        break;
 
663
      else
 
664
        bytes_read += rc;
 
665
    }
 
666
      
 
667
  buf[bytes_read] = '\0';
 
668
 
 
669
  if (length)
 
670
    *length = bytes_read;
 
671
  
 
672
  *contents = buf;
 
673
 
 
674
  close (fd);
 
675
 
 
676
  return TRUE;
 
677
 
 
678
 error:
 
679
 
 
680
  close (fd);
 
681
  
 
682
  return FALSE;
 
683
}
 
684
 
 
685
static gboolean
 
686
get_contents_posix (const gchar  *filename,
 
687
                    gchar       **contents,
 
688
                    gsize        *length,
 
689
                    GError      **error)
 
690
{
 
691
  struct stat stat_buf;
 
692
  gint fd;
 
693
  gchar *display_filename = g_filename_display_name (filename);
 
694
 
 
695
  /* O_BINARY useful on Cygwin */
 
696
  fd = open (filename, O_RDONLY|O_BINARY);
 
697
 
 
698
  if (fd < 0)
 
699
    {
 
700
      int save_errno = errno;
 
701
 
 
702
      g_set_error (error,
 
703
                   G_FILE_ERROR,
 
704
                   g_file_error_from_errno (save_errno),
 
705
                   _("Failed to open file '%s': %s"),
 
706
                   display_filename, 
 
707
                   g_strerror (save_errno));
 
708
      g_free (display_filename);
 
709
 
 
710
      return FALSE;
 
711
    }
 
712
 
 
713
  /* I don't think this will ever fail, aside from ENOMEM, but. */
 
714
  if (fstat (fd, &stat_buf) < 0)
 
715
    {
 
716
      int save_errno = errno;
 
717
 
 
718
      close (fd);
 
719
      g_set_error (error,
 
720
                   G_FILE_ERROR,
 
721
                   g_file_error_from_errno (save_errno),
 
722
                   _("Failed to get attributes of file '%s': fstat() failed: %s"),
 
723
                   display_filename, 
 
724
                   g_strerror (save_errno));
 
725
      g_free (display_filename);
 
726
 
 
727
      return FALSE;
 
728
    }
 
729
 
 
730
  if (stat_buf.st_size > 0 && S_ISREG (stat_buf.st_mode))
 
731
    {
 
732
      gboolean retval = get_contents_regfile (display_filename,
 
733
                                              &stat_buf,
 
734
                                              fd,
 
735
                                              contents,
 
736
                                              length,
 
737
                                              error);
 
738
      g_free (display_filename);
 
739
 
 
740
      return retval;
 
741
    }
 
742
  else
 
743
    {
 
744
      FILE *f;
 
745
      gboolean retval;
 
746
 
 
747
      f = fdopen (fd, "r");
 
748
      
 
749
      if (f == NULL)
 
750
        {
 
751
          int save_errno = errno;
 
752
 
 
753
          g_set_error (error,
 
754
                       G_FILE_ERROR,
 
755
                       g_file_error_from_errno (save_errno),
 
756
                       _("Failed to open file '%s': fdopen() failed: %s"),
 
757
                       display_filename, 
 
758
                       g_strerror (save_errno));
 
759
          g_free (display_filename);
 
760
 
 
761
          return FALSE;
 
762
        }
 
763
  
 
764
      retval = get_contents_stdio (display_filename, f, contents, length, error);
 
765
      g_free (display_filename);
 
766
 
 
767
      return retval;
 
768
    }
 
769
}
 
770
 
 
771
#else  /* G_OS_WIN32 */
 
772
 
 
773
static gboolean
 
774
get_contents_win32 (const gchar  *filename,
 
775
                    gchar       **contents,
 
776
                    gsize        *length,
 
777
                    GError      **error)
 
778
{
 
779
  FILE *f;
 
780
  gboolean retval;
 
781
  gchar *display_filename = g_filename_display_name (filename);
 
782
  int save_errno;
 
783
  
 
784
  f = g_fopen (filename, "rb");
 
785
  save_errno = errno;
 
786
 
 
787
  if (f == NULL)
 
788
    {
 
789
      g_set_error (error,
 
790
                   G_FILE_ERROR,
 
791
                   g_file_error_from_errno (save_errno),
 
792
                   _("Failed to open file '%s': %s"),
 
793
                   display_filename,
 
794
                   g_strerror (save_errno));
 
795
      g_free (display_filename);
 
796
 
 
797
      return FALSE;
 
798
    }
 
799
  
 
800
  retval = get_contents_stdio (display_filename, f, contents, length, error);
 
801
  g_free (display_filename);
 
802
 
 
803
  return retval;
 
804
}
 
805
 
 
806
#endif
 
807
 
 
808
/**
 
809
 * g_file_get_contents:
 
810
 * @filename: (type filename): name of a file to read contents from, in the GLib file name encoding
 
811
 * @contents: (out) (array length=length) (element-type guint8): location to store an allocated string, use g_free() to free
 
812
 *     the returned string
 
813
 * @length: (allow-none): location to store length in bytes of the contents, or %NULL
 
814
 * @error: return location for a #GError, or %NULL
 
815
 *
 
816
 * Reads an entire file into allocated memory, with good error
 
817
 * checking.
 
818
 *
 
819
 * If the call was successful, it returns %TRUE and sets @contents to the file
 
820
 * contents and @length to the length of the file contents in bytes. The string
 
821
 * stored in @contents will be nul-terminated, so for text files you can pass
 
822
 * %NULL for the @length argument. If the call was not successful, it returns
 
823
 * %FALSE and sets @error. The error domain is #G_FILE_ERROR. Possible error
 
824
 * codes are those in the #GFileError enumeration. In the error case,
 
825
 * @contents is set to %NULL and @length is set to zero.
 
826
 *
 
827
 * Return value: %TRUE on success, %FALSE if an error occurred
 
828
 **/
 
829
gboolean
 
830
g_file_get_contents (const gchar  *filename,
 
831
                     gchar       **contents,
 
832
                     gsize        *length,
 
833
                     GError      **error)
 
834
{  
 
835
  g_return_val_if_fail (filename != NULL, FALSE);
 
836
  g_return_val_if_fail (contents != NULL, FALSE);
 
837
 
 
838
  *contents = NULL;
 
839
  if (length)
 
840
    *length = 0;
 
841
 
 
842
#ifdef G_OS_WIN32
 
843
  return get_contents_win32 (filename, contents, length, error);
 
844
#else
 
845
  return get_contents_posix (filename, contents, length, error);
 
846
#endif
 
847
}
 
848
 
 
849
static gboolean
 
850
rename_file (const char  *old_name,
 
851
             const char  *new_name,
 
852
             GError     **err)
 
853
{
 
854
  errno = 0;
 
855
  if (g_rename (old_name, new_name) == -1)
 
856
    {
 
857
      int save_errno = errno;
 
858
      gchar *display_old_name = g_filename_display_name (old_name);
 
859
      gchar *display_new_name = g_filename_display_name (new_name);
 
860
 
 
861
      g_set_error (err,
 
862
                   G_FILE_ERROR,
 
863
                   g_file_error_from_errno (save_errno),
 
864
                   _("Failed to rename file '%s' to '%s': g_rename() failed: %s"),
 
865
                   display_old_name,
 
866
                   display_new_name,
 
867
                   g_strerror (save_errno));
 
868
 
 
869
      g_free (display_old_name);
 
870
      g_free (display_new_name);
 
871
      
 
872
      return FALSE;
 
873
    }
 
874
  
 
875
  return TRUE;
 
876
}
 
877
 
 
878
static gchar *
 
879
write_to_temp_file (const gchar  *contents,
 
880
                    gssize        length,
 
881
                    const gchar  *dest_file,
 
882
                    GError      **err)
 
883
{
 
884
  gchar *tmp_name;
 
885
  gchar *display_name;
 
886
  gchar *retval;
 
887
  FILE *file;
 
888
  gint fd;
 
889
  int save_errno;
 
890
 
 
891
  retval = NULL;
 
892
  
 
893
  tmp_name = g_strdup_printf ("%s.XXXXXX", dest_file);
 
894
 
 
895
  errno = 0;
 
896
  fd = g_mkstemp_full (tmp_name, O_RDWR | O_BINARY, 0666);
 
897
  save_errno = errno;
 
898
 
 
899
  display_name = g_filename_display_name (tmp_name);
 
900
      
 
901
  if (fd == -1)
 
902
    {
 
903
      g_set_error (err,
 
904
                   G_FILE_ERROR,
 
905
                   g_file_error_from_errno (save_errno),
 
906
                   _("Failed to create file '%s': %s"),
 
907
                   display_name, g_strerror (save_errno));
 
908
      
 
909
      goto out;
 
910
    }
 
911
 
 
912
  errno = 0;
 
913
  file = fdopen (fd, "wb");
 
914
  if (!file)
 
915
    {
 
916
      save_errno = errno;
 
917
      g_set_error (err,
 
918
                   G_FILE_ERROR,
 
919
                   g_file_error_from_errno (save_errno),
 
920
                   _("Failed to open file '%s' for writing: fdopen() failed: %s"),
 
921
                   display_name,
 
922
                   g_strerror (save_errno));
 
923
 
 
924
      close (fd);
 
925
      g_unlink (tmp_name);
 
926
      
 
927
      goto out;
 
928
    }
 
929
 
 
930
  if (length > 0)
 
931
    {
 
932
      gsize n_written;
 
933
      
 
934
      errno = 0;
 
935
 
 
936
      n_written = fwrite (contents, 1, length, file);
 
937
 
 
938
      if (n_written < length)
 
939
        {
 
940
          save_errno = errno;
 
941
      
 
942
          g_set_error (err,
 
943
                       G_FILE_ERROR,
 
944
                       g_file_error_from_errno (save_errno),
 
945
                       _("Failed to write file '%s': fwrite() failed: %s"),
 
946
                       display_name,
 
947
                       g_strerror (save_errno));
 
948
 
 
949
          fclose (file);
 
950
          g_unlink (tmp_name);
 
951
          
 
952
          goto out;
 
953
        }
 
954
    }
 
955
 
 
956
  errno = 0;
 
957
  if (fflush (file) != 0)
 
958
    { 
 
959
      save_errno = errno;
 
960
      
 
961
      g_set_error (err,
 
962
                   G_FILE_ERROR,
 
963
                   g_file_error_from_errno (save_errno),
 
964
                   _("Failed to write file '%s': fflush() failed: %s"),
 
965
                   display_name, 
 
966
                   g_strerror (save_errno));
 
967
 
 
968
      fclose (file);
 
969
      g_unlink (tmp_name);
 
970
      
 
971
      goto out;
 
972
    }
 
973
 
 
974
#ifdef BTRFS_SUPER_MAGIC
 
975
  {
 
976
    struct statfs buf;
 
977
 
 
978
    /* On Linux, on btrfs, skip the fsync since rename-over-existing is
 
979
     * guaranteed to be atomic and this is the only case in which we
 
980
     * would fsync() anyway.
 
981
     */
 
982
 
 
983
    if (fstatfs (fd, &buf) == 0 && buf.f_type == BTRFS_SUPER_MAGIC)
 
984
      goto no_fsync;
 
985
  }
 
986
#endif
 
987
  
 
988
#ifdef HAVE_FSYNC
 
989
  {
 
990
    struct stat statbuf;
 
991
 
 
992
    errno = 0;
 
993
    /* If the final destination exists and is > 0 bytes, we want to sync the
 
994
     * newly written file to ensure the data is on disk when we rename over
 
995
     * the destination. Otherwise if we get a system crash we can lose both
 
996
     * the new and the old file on some filesystems. (I.E. those that don't
 
997
     * guarantee the data is written to the disk before the metadata.)
 
998
     */
 
999
    if (g_lstat (dest_file, &statbuf) == 0 &&
 
1000
        statbuf.st_size > 0 &&
 
1001
        fsync (fileno (file)) != 0)
 
1002
      {
 
1003
        save_errno = errno;
 
1004
 
 
1005
        g_set_error (err,
 
1006
                     G_FILE_ERROR,
 
1007
                     g_file_error_from_errno (save_errno),
 
1008
                     _("Failed to write file '%s': fsync() failed: %s"),
 
1009
                     display_name,
 
1010
                     g_strerror (save_errno));
 
1011
 
 
1012
        fclose (file);
 
1013
        g_unlink (tmp_name);
 
1014
 
 
1015
        goto out;
 
1016
      }
 
1017
  }
 
1018
#endif
 
1019
 
 
1020
#ifdef BTRFS_SUPER_MAGIC
 
1021
 no_fsync:
 
1022
#endif
 
1023
  
 
1024
  errno = 0;
 
1025
  if (fclose (file) == EOF)
 
1026
    { 
 
1027
      save_errno = errno;
 
1028
      
 
1029
      g_set_error (err,
 
1030
                   G_FILE_ERROR,
 
1031
                   g_file_error_from_errno (save_errno),
 
1032
                   _("Failed to close file '%s': fclose() failed: %s"),
 
1033
                   display_name, 
 
1034
                   g_strerror (save_errno));
 
1035
 
 
1036
      fclose (file);
 
1037
      g_unlink (tmp_name);
 
1038
      
 
1039
      goto out;
 
1040
    }
 
1041
 
 
1042
  retval = g_strdup (tmp_name);
 
1043
  
 
1044
 out:
 
1045
  g_free (tmp_name);
 
1046
  g_free (display_name);
 
1047
  
 
1048
  return retval;
 
1049
}
 
1050
 
 
1051
/**
 
1052
 * g_file_set_contents:
 
1053
 * @filename: (type filename): name of a file to write @contents to, in the GLib file name
 
1054
 *   encoding
 
1055
 * @contents: (array length=length) (element-type guint8): string to write to the file
 
1056
 * @length: length of @contents, or -1 if @contents is a nul-terminated string
 
1057
 * @error: return location for a #GError, or %NULL
 
1058
 *
 
1059
 * Writes all of @contents to a file named @filename, with good error checking.
 
1060
 * If a file called @filename already exists it will be overwritten.
 
1061
 *
 
1062
 * This write is atomic in the sense that it is first written to a temporary
 
1063
 * file which is then renamed to the final name. Notes:
 
1064
 * <itemizedlist>
 
1065
 * <listitem>
 
1066
 *    On Unix, if @filename already exists hard links to @filename will break.
 
1067
 *    Also since the file is recreated, existing permissions, access control
 
1068
 *    lists, metadata etc. may be lost. If @filename is a symbolic link,
 
1069
 *    the link itself will be replaced, not the linked file.
 
1070
 * </listitem>
 
1071
 * <listitem>
 
1072
 *   On Windows renaming a file will not remove an existing file with the
 
1073
 *   new name, so on Windows there is a race condition between the existing
 
1074
 *   file being removed and the temporary file being renamed.
 
1075
 * </listitem>
 
1076
 * <listitem>
 
1077
 *   On Windows there is no way to remove a file that is open to some
 
1078
 *   process, or mapped into memory. Thus, this function will fail if
 
1079
 *   @filename already exists and is open.
 
1080
 * </listitem>
 
1081
 * </itemizedlist>
 
1082
 *
 
1083
 * If the call was successful, it returns %TRUE. If the call was not successful,
 
1084
 * it returns %FALSE and sets @error. The error domain is #G_FILE_ERROR.
 
1085
 * Possible error codes are those in the #GFileError enumeration.
 
1086
 *
 
1087
 * Note that the name for the temporary file is constructed by appending up
 
1088
 * to 7 characters to @filename.
 
1089
 *
 
1090
 * Return value: %TRUE on success, %FALSE if an error occurred
 
1091
 *
 
1092
 * Since: 2.8
 
1093
 **/
 
1094
gboolean
 
1095
g_file_set_contents (const gchar  *filename,
 
1096
                     const gchar  *contents,
 
1097
                     gssize        length,
 
1098
                     GError      **error)
 
1099
{
 
1100
  gchar *tmp_filename;
 
1101
  gboolean retval;
 
1102
  GError *rename_error = NULL;
 
1103
  
 
1104
  g_return_val_if_fail (filename != NULL, FALSE);
 
1105
  g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
 
1106
  g_return_val_if_fail (contents != NULL || length == 0, FALSE);
 
1107
  g_return_val_if_fail (length >= -1, FALSE);
 
1108
  
 
1109
  if (length == -1)
 
1110
    length = strlen (contents);
 
1111
 
 
1112
  tmp_filename = write_to_temp_file (contents, length, filename, error);
 
1113
  
 
1114
  if (!tmp_filename)
 
1115
    {
 
1116
      retval = FALSE;
 
1117
      goto out;
 
1118
    }
 
1119
 
 
1120
  if (!rename_file (tmp_filename, filename, &rename_error))
 
1121
    {
 
1122
#ifndef G_OS_WIN32
 
1123
 
 
1124
      g_unlink (tmp_filename);
 
1125
      g_propagate_error (error, rename_error);
 
1126
      retval = FALSE;
 
1127
      goto out;
 
1128
 
 
1129
#else /* G_OS_WIN32 */
 
1130
      
 
1131
      /* Renaming failed, but on Windows this may just mean
 
1132
       * the file already exists. So if the target file
 
1133
       * exists, try deleting it and do the rename again.
 
1134
       */
 
1135
      if (!g_file_test (filename, G_FILE_TEST_EXISTS))
 
1136
        {
 
1137
          g_unlink (tmp_filename);
 
1138
          g_propagate_error (error, rename_error);
 
1139
          retval = FALSE;
 
1140
          goto out;
 
1141
        }
 
1142
 
 
1143
      g_error_free (rename_error);
 
1144
      
 
1145
      if (g_unlink (filename) == -1)
 
1146
        {
 
1147
          gchar *display_filename = g_filename_display_name (filename);
 
1148
 
 
1149
          int save_errno = errno;
 
1150
          
 
1151
          g_set_error (error,
 
1152
                       G_FILE_ERROR,
 
1153
                       g_file_error_from_errno (save_errno),
 
1154
                       _("Existing file '%s' could not be removed: g_unlink() failed: %s"),
 
1155
                       display_filename,
 
1156
                       g_strerror (save_errno));
 
1157
 
 
1158
          g_free (display_filename);
 
1159
          g_unlink (tmp_filename);
 
1160
          retval = FALSE;
 
1161
          goto out;
 
1162
        }
 
1163
      
 
1164
      if (!rename_file (tmp_filename, filename, error))
 
1165
        {
 
1166
          g_unlink (tmp_filename);
 
1167
          retval = FALSE;
 
1168
          goto out;
 
1169
        }
 
1170
 
 
1171
#endif
 
1172
    }
 
1173
 
 
1174
  retval = TRUE;
 
1175
  
 
1176
 out:
 
1177
  g_free (tmp_filename);
 
1178
  return retval;
 
1179
}
 
1180
 
 
1181
/*
 
1182
 * get_tmp_file based on the mkstemp implementation from the GNU C library.
 
1183
 * Copyright (C) 1991,92,93,94,95,96,97,98,99 Free Software Foundation, Inc.
 
1184
 */
 
1185
typedef gint (*GTmpFileCallback) (gchar *, gint, gint);
 
1186
 
 
1187
static gint
 
1188
get_tmp_file (gchar            *tmpl,
 
1189
              GTmpFileCallback  f,
 
1190
              int               flags,
 
1191
              int               mode)
 
1192
{
 
1193
  char *XXXXXX;
 
1194
  int count, fd;
 
1195
  static const char letters[] =
 
1196
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
 
1197
  static const int NLETTERS = sizeof (letters) - 1;
 
1198
  glong value;
 
1199
  GTimeVal tv;
 
1200
  static int counter = 0;
 
1201
 
 
1202
  g_return_val_if_fail (tmpl != NULL, -1);
 
1203
 
 
1204
  /* find the last occurrence of "XXXXXX" */
 
1205
  XXXXXX = g_strrstr (tmpl, "XXXXXX");
 
1206
 
 
1207
  if (!XXXXXX || strncmp (XXXXXX, "XXXXXX", 6))
 
1208
    {
 
1209
      errno = EINVAL;
 
1210
      return -1;
 
1211
    }
 
1212
 
 
1213
  /* Get some more or less random data.  */
 
1214
  g_get_current_time (&tv);
 
1215
  value = (tv.tv_usec ^ tv.tv_sec) + counter++;
 
1216
 
 
1217
  for (count = 0; count < 100; value += 7777, ++count)
 
1218
    {
 
1219
      glong v = value;
 
1220
 
 
1221
      /* Fill in the random bits.  */
 
1222
      XXXXXX[0] = letters[v % NLETTERS];
 
1223
      v /= NLETTERS;
 
1224
      XXXXXX[1] = letters[v % NLETTERS];
 
1225
      v /= NLETTERS;
 
1226
      XXXXXX[2] = letters[v % NLETTERS];
 
1227
      v /= NLETTERS;
 
1228
      XXXXXX[3] = letters[v % NLETTERS];
 
1229
      v /= NLETTERS;
 
1230
      XXXXXX[4] = letters[v % NLETTERS];
 
1231
      v /= NLETTERS;
 
1232
      XXXXXX[5] = letters[v % NLETTERS];
 
1233
 
 
1234
      fd = f (tmpl, flags, mode);
 
1235
 
 
1236
      if (fd >= 0)
 
1237
        return fd;
 
1238
      else if (errno != EEXIST)
 
1239
        /* Any other error will apply also to other names we might
 
1240
         *  try, and there are 2^32 or so of them, so give up now.
 
1241
         */
 
1242
        return -1;
 
1243
    }
 
1244
 
 
1245
  /* We got out of the loop because we ran out of combinations to try.  */
 
1246
  errno = EEXIST;
 
1247
  return -1;
 
1248
}
 
1249
 
 
1250
gint
 
1251
wrap_mkdir (gchar *tmpl,
 
1252
            int    flags G_GNUC_UNUSED,
 
1253
            int    mode)
 
1254
{
 
1255
  /* tmpl is in UTF-8 on Windows, thus use g_mkdir() */
 
1256
  return g_mkdir (tmpl, mode);
 
1257
}
 
1258
 
 
1259
/**
 
1260
 * g_mkdtemp_full:
 
1261
 * @tmpl: (type filename): template directory name
 
1262
 * @mode: permissions to create the temporary directory with
 
1263
 *
 
1264
 * Creates a temporary directory. See the mkdtemp() documentation
 
1265
 * on most UNIX-like systems.
 
1266
 *
 
1267
 * The parameter is a string that should follow the rules for
 
1268
 * mkdtemp() templates, i.e. contain the string "XXXXXX".
 
1269
 * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
 
1270
 * sequence does not have to occur at the very end of the template
 
1271
 * and you can pass a @mode. The X string will be modified to form
 
1272
 * the name of a directory that didn't exist. The string should be
 
1273
 * in the GLib file name encoding. Most importantly, on Windows it
 
1274
 * should be in UTF-8.
 
1275
 *
 
1276
 * Return value: A pointer to @tmpl, which has been modified
 
1277
 *     to hold the directory name. In case of errors, %NULL is
 
1278
 *     returned, and %errno will be set.
 
1279
 *
 
1280
 * Since: 2.26
 
1281
 */
 
1282
gchar *
 
1283
g_mkdtemp_full (gchar *tmpl,
 
1284
                gint   mode)
 
1285
{
 
1286
  if (get_tmp_file (tmpl, wrap_mkdir, 0, mode) == -1)
 
1287
    return NULL;
 
1288
  else
 
1289
    return tmpl;
 
1290
}
 
1291
 
 
1292
/**
 
1293
 * g_mkdtemp:
 
1294
 * @tmpl: (type filename): template directory name
 
1295
 *
 
1296
 * Creates a temporary directory. See the mkdtemp() documentation
 
1297
 * on most UNIX-like systems.
 
1298
 *
 
1299
 * The parameter is a string that should follow the rules for
 
1300
 * mkdtemp() templates, i.e. contain the string "XXXXXX".
 
1301
 * g_mkdtemp() is slightly more flexible than mkdtemp() in that the
 
1302
 * sequence does not have to occur at the very end of the template
 
1303
 * and you can pass a @mode and additional @flags. The X string will
 
1304
 * be modified to form the name of a directory that didn't exist.
 
1305
 * The string should be in the GLib file name encoding. Most importantly,
 
1306
 * on Windows it should be in UTF-8.
 
1307
 *
 
1308
 * Return value: A pointer to @tmpl, which has been modified
 
1309
 *     to hold the directory name.  In case of errors, %NULL is
 
1310
 *     returned and %errno will be set.
 
1311
 *
 
1312
 * Since: 2.26
 
1313
 */
 
1314
gchar *
 
1315
g_mkdtemp (gchar *tmpl)
 
1316
{
 
1317
  return g_mkdtemp_full (tmpl, 0700);
 
1318
}
 
1319
 
 
1320
/**
 
1321
 * g_mkstemp_full:
 
1322
 * @tmpl: (type filename): template filename
 
1323
 * @flags: flags to pass to an open() call in addition to O_EXCL
 
1324
 *     and O_CREAT, which are passed automatically
 
1325
 * @mode: permissions to create the temporary file with
 
1326
 *
 
1327
 * Opens a temporary file. See the mkstemp() documentation
 
1328
 * on most UNIX-like systems.
 
1329
 *
 
1330
 * The parameter is a string that should follow the rules for
 
1331
 * mkstemp() templates, i.e. contain the string "XXXXXX".
 
1332
 * g_mkstemp_full() is slightly more flexible than mkstemp()
 
1333
 * in that the sequence does not have to occur at the very end of the
 
1334
 * template and you can pass a @mode and additional @flags. The X
 
1335
 * string will be modified to form the name of a file that didn't exist.
 
1336
 * The string should be in the GLib file name encoding. Most importantly,
 
1337
 * on Windows it should be in UTF-8.
 
1338
 *
 
1339
 * Return value: A file handle (as from open()) to the file
 
1340
 *     opened for reading and writing. The file handle should be
 
1341
 *     closed with close(). In case of errors, -1 is returned
 
1342
 *     and %errno will be set.
 
1343
 *
 
1344
 * Since: 2.22
 
1345
 */
 
1346
gint
 
1347
g_mkstemp_full (gchar *tmpl,
 
1348
                gint   flags,
 
1349
                gint   mode)
 
1350
{
 
1351
  /* tmpl is in UTF-8 on Windows, thus use g_open() */
 
1352
  return get_tmp_file (tmpl, (GTmpFileCallback) g_open,
 
1353
                       flags | O_CREAT | O_EXCL, mode);
 
1354
}
 
1355
 
 
1356
/**
 
1357
 * g_mkstemp:
 
1358
 * @tmpl: (type filename): template filename
 
1359
 *
 
1360
 * Opens a temporary file. See the mkstemp() documentation
 
1361
 * on most UNIX-like systems.
 
1362
 *
 
1363
 * The parameter is a string that should follow the rules for
 
1364
 * mkstemp() templates, i.e. contain the string "XXXXXX".
 
1365
 * g_mkstemp() is slightly more flexible than mkstemp() in that the
 
1366
 * sequence does not have to occur at the very end of the template.
 
1367
 * The X string will be modified to form the name of a file that
 
1368
 * didn't exist. The string should be in the GLib file name encoding.
 
1369
 * Most importantly, on Windows it should be in UTF-8.
 
1370
 *
 
1371
 * Return value: A file handle (as from open()) to the file
 
1372
 *     opened for reading and writing. The file is opened in binary
 
1373
 *     mode on platforms where there is a difference. The file handle
 
1374
 *     should be closed with close(). In case of errors, -1 is
 
1375
 *     returned and %errno will be set.
 
1376
 */
 
1377
gint
 
1378
g_mkstemp (gchar *tmpl)
 
1379
{
 
1380
  return g_mkstemp_full (tmpl, O_RDWR | O_BINARY, 0600);
 
1381
}
 
1382
 
 
1383
static gint
 
1384
g_get_tmp_name (const gchar      *tmpl,
 
1385
                gchar           **name_used,
 
1386
                GTmpFileCallback  f,
 
1387
                gint              flags,
 
1388
                gint              mode,
 
1389
                GError          **error)
 
1390
{
 
1391
  int retval;
 
1392
  const char *tmpdir;
 
1393
  const char *sep;
 
1394
  char *fulltemplate;
 
1395
  const char *slash;
 
1396
 
 
1397
  if (tmpl == NULL)
 
1398
    tmpl = ".XXXXXX";
 
1399
 
 
1400
  if ((slash = strchr (tmpl, G_DIR_SEPARATOR)) != NULL
 
1401
#ifdef G_OS_WIN32
 
1402
      || (strchr (tmpl, '/') != NULL && (slash = "/"))
 
1403
#endif
 
1404
      )
 
1405
    {
 
1406
      gchar *display_tmpl = g_filename_display_name (tmpl);
 
1407
      char c[2];
 
1408
      c[0] = *slash;
 
1409
      c[1] = '\0';
 
1410
 
 
1411
      g_set_error (error,
 
1412
                   G_FILE_ERROR,
 
1413
                   G_FILE_ERROR_FAILED,
 
1414
                   _("Template '%s' invalid, should not contain a '%s'"),
 
1415
                   display_tmpl, c);
 
1416
      g_free (display_tmpl);
 
1417
 
 
1418
      return -1;
 
1419
    }
 
1420
 
 
1421
  if (strstr (tmpl, "XXXXXX") == NULL)
 
1422
    {
 
1423
      gchar *display_tmpl = g_filename_display_name (tmpl);
 
1424
      g_set_error (error,
 
1425
                   G_FILE_ERROR,
 
1426
                   G_FILE_ERROR_FAILED,
 
1427
                   _("Template '%s' doesn't contain XXXXXX"),
 
1428
                   display_tmpl);
 
1429
      g_free (display_tmpl);
 
1430
      return -1;
 
1431
    }
 
1432
 
 
1433
  tmpdir = g_get_tmp_dir ();
 
1434
 
 
1435
  if (G_IS_DIR_SEPARATOR (tmpdir [strlen (tmpdir) - 1]))
 
1436
    sep = "";
 
1437
  else
 
1438
    sep = G_DIR_SEPARATOR_S;
 
1439
 
 
1440
  fulltemplate = g_strconcat (tmpdir, sep, tmpl, NULL);
 
1441
 
 
1442
  retval = get_tmp_file (fulltemplate, f, flags, mode);
 
1443
  if (retval == -1)
 
1444
    {
 
1445
      int save_errno = errno;
 
1446
      gchar *display_fulltemplate = g_filename_display_name (fulltemplate);
 
1447
 
 
1448
      g_set_error (error,
 
1449
                   G_FILE_ERROR,
 
1450
                   g_file_error_from_errno (save_errno),
 
1451
                   _("Failed to create file '%s': %s"),
 
1452
                   display_fulltemplate, g_strerror (save_errno));
 
1453
      g_free (display_fulltemplate);
 
1454
      g_free (fulltemplate);
 
1455
      return -1;
 
1456
    }
 
1457
 
 
1458
  *name_used = fulltemplate;
 
1459
 
 
1460
  return retval;
 
1461
}
 
1462
 
 
1463
/**
 
1464
 * g_file_open_tmp:
 
1465
 * @tmpl: (type filename) (allow-none): Template for file name, as in
 
1466
 *     g_mkstemp(), basename only, or %NULL for a default template
 
1467
 * @name_used: (out) (type filename): location to store actual name used,
 
1468
 *     or %NULL
 
1469
 * @error: return location for a #GError
 
1470
 *
 
1471
 * Opens a file for writing in the preferred directory for temporary
 
1472
 * files (as returned by g_get_tmp_dir()).
 
1473
 *
 
1474
 * @tmpl should be a string in the GLib file name encoding containing
 
1475
 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
 
1476
 * However, unlike these functions, the template should only be a
 
1477
 * basename, no directory components are allowed. If template is
 
1478
 * %NULL, a default template is used.
 
1479
 *
 
1480
 * Note that in contrast to g_mkstemp() (and mkstemp()) @tmpl is not
 
1481
 * modified, and might thus be a read-only literal string.
 
1482
 *
 
1483
 * Upon success, and if @name_used is non-%NULL, the actual name used
 
1484
 * is returned in @name_used. This string should be freed with g_free()
 
1485
 * when not needed any longer. The returned name is in the GLib file
 
1486
 * name encoding.
 
1487
 *
 
1488
 * Return value: A file handle (as from open()) to the file opened for
 
1489
 *     reading and writing. The file is opened in binary mode on platforms
 
1490
 *     where there is a difference. The file handle should be closed with
 
1491
 *     close(). In case of errors, -1 is returned and @error will be set.
 
1492
 */
 
1493
gint
 
1494
g_file_open_tmp (const gchar  *tmpl,
 
1495
                 gchar       **name_used,
 
1496
                 GError      **error)
 
1497
{
 
1498
  gchar *fulltemplate;
 
1499
  gint result;
 
1500
 
 
1501
  result = g_get_tmp_name (tmpl, &fulltemplate,
 
1502
                           (GTmpFileCallback) g_open,
 
1503
                           O_CREAT | O_EXCL | O_RDWR | O_BINARY,
 
1504
                           0600,
 
1505
                           error);
 
1506
  if (result != -1)
 
1507
    {
 
1508
      if (name_used)
 
1509
        *name_used = fulltemplate;
 
1510
      else
 
1511
        g_free (fulltemplate);
 
1512
    }
 
1513
 
 
1514
  return result;
 
1515
}
 
1516
 
 
1517
/**
 
1518
 * g_dir_make_tmp:
 
1519
 * @tmpl: (type filename) (allow-none): Template for directory name,
 
1520
 *     as in g_mkdtemp(), basename only, or %NULL for a default template
 
1521
 * @error: return location for a #GError
 
1522
 *
 
1523
 * Creates a subdirectory in the preferred directory for temporary
 
1524
 * files (as returned by g_get_tmp_dir()).
 
1525
 *
 
1526
 * @tmpl should be a string in the GLib file name encoding containing
 
1527
 * a sequence of six 'X' characters, as the parameter to g_mkstemp().
 
1528
 * However, unlike these functions, the template should only be a
 
1529
 * basename, no directory components are allowed. If template is
 
1530
 * %NULL, a default template is used.
 
1531
 *
 
1532
 * Note that in contrast to g_mkdtemp() (and mkdtemp()) @tmpl is not
 
1533
 * modified, and might thus be a read-only literal string.
 
1534
 *
 
1535
 * Return value: (type filename): The actual name used. This string
 
1536
 *     should be freed with g_free() when not needed any longer and is
 
1537
 *     is in the GLib file name encoding. In case of errors, %NULL is
 
1538
 *     returned and @error will be set.
 
1539
 *
 
1540
 * Since: 2.30
 
1541
 */
 
1542
gchar *
 
1543
g_dir_make_tmp (const gchar  *tmpl,
 
1544
                GError      **error)
 
1545
{
 
1546
  gchar *fulltemplate;
 
1547
 
 
1548
  if (g_get_tmp_name (tmpl, &fulltemplate, wrap_mkdir, 0, 0700, error) == -1)
 
1549
    return NULL;
 
1550
  else
 
1551
    return fulltemplate;
 
1552
}
 
1553
 
 
1554
static gchar *
 
1555
g_build_path_va (const gchar  *separator,
 
1556
                 const gchar  *first_element,
 
1557
                 va_list      *args,
 
1558
                 gchar       **str_array)
 
1559
{
 
1560
  GString *result;
 
1561
  gint separator_len = strlen (separator);
 
1562
  gboolean is_first = TRUE;
 
1563
  gboolean have_leading = FALSE;
 
1564
  const gchar *single_element = NULL;
 
1565
  const gchar *next_element;
 
1566
  const gchar *last_trailing = NULL;
 
1567
  gint i = 0;
 
1568
 
 
1569
  result = g_string_new (NULL);
 
1570
 
 
1571
  if (str_array)
 
1572
    next_element = str_array[i++];
 
1573
  else
 
1574
    next_element = first_element;
 
1575
 
 
1576
  while (TRUE)
 
1577
    {
 
1578
      const gchar *element;
 
1579
      const gchar *start;
 
1580
      const gchar *end;
 
1581
 
 
1582
      if (next_element)
 
1583
        {
 
1584
          element = next_element;
 
1585
          if (str_array)
 
1586
            next_element = str_array[i++];
 
1587
          else
 
1588
            next_element = va_arg (*args, gchar *);
 
1589
        }
 
1590
      else
 
1591
        break;
 
1592
 
 
1593
      /* Ignore empty elements */
 
1594
      if (!*element)
 
1595
        continue;
 
1596
      
 
1597
      start = element;
 
1598
 
 
1599
      if (separator_len)
 
1600
        {
 
1601
          while (strncmp (start, separator, separator_len) == 0)
 
1602
            start += separator_len;
 
1603
        }
 
1604
 
 
1605
      end = start + strlen (start);
 
1606
      
 
1607
      if (separator_len)
 
1608
        {
 
1609
          while (end >= start + separator_len &&
 
1610
                 strncmp (end - separator_len, separator, separator_len) == 0)
 
1611
            end -= separator_len;
 
1612
          
 
1613
          last_trailing = end;
 
1614
          while (last_trailing >= element + separator_len &&
 
1615
                 strncmp (last_trailing - separator_len, separator, separator_len) == 0)
 
1616
            last_trailing -= separator_len;
 
1617
 
 
1618
          if (!have_leading)
 
1619
            {
 
1620
              /* If the leading and trailing separator strings are in the
 
1621
               * same element and overlap, the result is exactly that element
 
1622
               */
 
1623
              if (last_trailing <= start)
 
1624
                single_element = element;
 
1625
                  
 
1626
              g_string_append_len (result, element, start - element);
 
1627
              have_leading = TRUE;
 
1628
            }
 
1629
          else
 
1630
            single_element = NULL;
 
1631
        }
 
1632
 
 
1633
      if (end == start)
 
1634
        continue;
 
1635
 
 
1636
      if (!is_first)
 
1637
        g_string_append (result, separator);
 
1638
      
 
1639
      g_string_append_len (result, start, end - start);
 
1640
      is_first = FALSE;
 
1641
    }
 
1642
 
 
1643
  if (single_element)
 
1644
    {
 
1645
      g_string_free (result, TRUE);
 
1646
      return g_strdup (single_element);
 
1647
    }
 
1648
  else
 
1649
    {
 
1650
      if (last_trailing)
 
1651
        g_string_append (result, last_trailing);
 
1652
  
 
1653
      return g_string_free (result, FALSE);
 
1654
    }
 
1655
}
 
1656
 
 
1657
/**
 
1658
 * g_build_pathv:
 
1659
 * @separator: a string used to separator the elements of the path.
 
1660
 * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
 
1661
 * 
 
1662
 * Behaves exactly like g_build_path(), but takes the path elements 
 
1663
 * as a string array, instead of varargs. This function is mainly
 
1664
 * meant for language bindings.
 
1665
 *
 
1666
 * Return value: a newly-allocated string that must be freed with g_free().
 
1667
 *
 
1668
 * Since: 2.8
 
1669
 */
 
1670
gchar *
 
1671
g_build_pathv (const gchar  *separator,
 
1672
               gchar       **args)
 
1673
{
 
1674
  if (!args)
 
1675
    return NULL;
 
1676
 
 
1677
  return g_build_path_va (separator, NULL, NULL, args);
 
1678
}
 
1679
 
 
1680
 
 
1681
/**
 
1682
 * g_build_path:
 
1683
 * @separator: a string used to separator the elements of the path.
 
1684
 * @first_element: the first element in the path
 
1685
 * @...: remaining elements in path, terminated by %NULL
 
1686
 * 
 
1687
 * Creates a path from a series of elements using @separator as the
 
1688
 * separator between elements. At the boundary between two elements,
 
1689
 * any trailing occurrences of separator in the first element, or
 
1690
 * leading occurrences of separator in the second element are removed
 
1691
 * and exactly one copy of the separator is inserted.
 
1692
 *
 
1693
 * Empty elements are ignored.
 
1694
 *
 
1695
 * The number of leading copies of the separator on the result is
 
1696
 * the same as the number of leading copies of the separator on
 
1697
 * the first non-empty element.
 
1698
 *
 
1699
 * The number of trailing copies of the separator on the result is
 
1700
 * the same as the number of trailing copies of the separator on
 
1701
 * the last non-empty element. (Determination of the number of
 
1702
 * trailing copies is done without stripping leading copies, so
 
1703
 * if the separator is <literal>ABA</literal>, <literal>ABABA</literal>
 
1704
 * has 1 trailing copy.)
 
1705
 *
 
1706
 * However, if there is only a single non-empty element, and there
 
1707
 * are no characters in that element not part of the leading or
 
1708
 * trailing separators, then the result is exactly the original value
 
1709
 * of that element.
 
1710
 *
 
1711
 * Other than for determination of the number of leading and trailing
 
1712
 * copies of the separator, elements consisting only of copies
 
1713
 * of the separator are ignored.
 
1714
 * 
 
1715
 * Return value: a newly-allocated string that must be freed with g_free().
 
1716
 **/
 
1717
gchar *
 
1718
g_build_path (const gchar *separator,
 
1719
              const gchar *first_element,
 
1720
              ...)
 
1721
{
 
1722
  gchar *str;
 
1723
  va_list args;
 
1724
 
 
1725
  g_return_val_if_fail (separator != NULL, NULL);
 
1726
 
 
1727
  va_start (args, first_element);
 
1728
  str = g_build_path_va (separator, first_element, &args, NULL);
 
1729
  va_end (args);
 
1730
 
 
1731
  return str;
 
1732
}
 
1733
 
 
1734
#ifdef G_OS_WIN32
 
1735
 
 
1736
static gchar *
 
1737
g_build_pathname_va (const gchar  *first_element,
 
1738
                     va_list      *args,
 
1739
                     gchar       **str_array)
 
1740
{
 
1741
  /* Code copied from g_build_pathv(), and modified to use two
 
1742
   * alternative single-character separators.
 
1743
   */
 
1744
  GString *result;
 
1745
  gboolean is_first = TRUE;
 
1746
  gboolean have_leading = FALSE;
 
1747
  const gchar *single_element = NULL;
 
1748
  const gchar *next_element;
 
1749
  const gchar *last_trailing = NULL;
 
1750
  gchar current_separator = '\\';
 
1751
  gint i = 0;
 
1752
 
 
1753
  result = g_string_new (NULL);
 
1754
 
 
1755
  if (str_array)
 
1756
    next_element = str_array[i++];
 
1757
  else
 
1758
    next_element = first_element;
 
1759
  
 
1760
  while (TRUE)
 
1761
    {
 
1762
      const gchar *element;
 
1763
      const gchar *start;
 
1764
      const gchar *end;
 
1765
 
 
1766
      if (next_element)
 
1767
        {
 
1768
          element = next_element;
 
1769
          if (str_array)
 
1770
            next_element = str_array[i++];
 
1771
          else
 
1772
            next_element = va_arg (*args, gchar *);
 
1773
        }
 
1774
      else
 
1775
        break;
 
1776
 
 
1777
      /* Ignore empty elements */
 
1778
      if (!*element)
 
1779
        continue;
 
1780
      
 
1781
      start = element;
 
1782
 
 
1783
      if (TRUE)
 
1784
        {
 
1785
          while (start &&
 
1786
                 (*start == '\\' || *start == '/'))
 
1787
            {
 
1788
              current_separator = *start;
 
1789
              start++;
 
1790
            }
 
1791
        }
 
1792
 
 
1793
      end = start + strlen (start);
 
1794
      
 
1795
      if (TRUE)
 
1796
        {
 
1797
          while (end >= start + 1 &&
 
1798
                 (end[-1] == '\\' || end[-1] == '/'))
 
1799
            {
 
1800
              current_separator = end[-1];
 
1801
              end--;
 
1802
            }
 
1803
          
 
1804
          last_trailing = end;
 
1805
          while (last_trailing >= element + 1 &&
 
1806
                 (last_trailing[-1] == '\\' || last_trailing[-1] == '/'))
 
1807
            last_trailing--;
 
1808
 
 
1809
          if (!have_leading)
 
1810
            {
 
1811
              /* If the leading and trailing separator strings are in the
 
1812
               * same element and overlap, the result is exactly that element
 
1813
               */
 
1814
              if (last_trailing <= start)
 
1815
                single_element = element;
 
1816
                  
 
1817
              g_string_append_len (result, element, start - element);
 
1818
              have_leading = TRUE;
 
1819
            }
 
1820
          else
 
1821
            single_element = NULL;
 
1822
        }
 
1823
 
 
1824
      if (end == start)
 
1825
        continue;
 
1826
 
 
1827
      if (!is_first)
 
1828
        g_string_append_len (result, &current_separator, 1);
 
1829
      
 
1830
      g_string_append_len (result, start, end - start);
 
1831
      is_first = FALSE;
 
1832
    }
 
1833
 
 
1834
  if (single_element)
 
1835
    {
 
1836
      g_string_free (result, TRUE);
 
1837
      return g_strdup (single_element);
 
1838
    }
 
1839
  else
 
1840
    {
 
1841
      if (last_trailing)
 
1842
        g_string_append (result, last_trailing);
 
1843
  
 
1844
      return g_string_free (result, FALSE);
 
1845
    }
 
1846
}
 
1847
 
 
1848
#endif
 
1849
 
 
1850
/**
 
1851
 * g_build_filenamev:
 
1852
 * @args: (array zero-terminated=1): %NULL-terminated array of strings containing the path elements.
 
1853
 * 
 
1854
 * Behaves exactly like g_build_filename(), but takes the path elements 
 
1855
 * as a string array, instead of varargs. This function is mainly
 
1856
 * meant for language bindings.
 
1857
 *
 
1858
 * Return value: a newly-allocated string that must be freed with g_free().
 
1859
 * 
 
1860
 * Since: 2.8
 
1861
 */
 
1862
gchar *
 
1863
g_build_filenamev (gchar **args)
 
1864
{
 
1865
  gchar *str;
 
1866
 
 
1867
#ifndef G_OS_WIN32
 
1868
  str = g_build_path_va (G_DIR_SEPARATOR_S, NULL, NULL, args);
 
1869
#else
 
1870
  str = g_build_pathname_va (NULL, NULL, args);
 
1871
#endif
 
1872
 
 
1873
  return str;
 
1874
}
 
1875
 
 
1876
/**
 
1877
 * g_build_filename:
 
1878
 * @first_element: the first element in the path
 
1879
 * @...: remaining elements in path, terminated by %NULL
 
1880
 * 
 
1881
 * Creates a filename from a series of elements using the correct
 
1882
 * separator for filenames.
 
1883
 *
 
1884
 * On Unix, this function behaves identically to <literal>g_build_path
 
1885
 * (G_DIR_SEPARATOR_S, first_element, ....)</literal>.
 
1886
 *
 
1887
 * On Windows, it takes into account that either the backslash
 
1888
 * (<literal>\</literal> or slash (<literal>/</literal>) can be used
 
1889
 * as separator in filenames, but otherwise behaves as on Unix. When
 
1890
 * file pathname separators need to be inserted, the one that last
 
1891
 * previously occurred in the parameters (reading from left to right)
 
1892
 * is used.
 
1893
 *
 
1894
 * No attempt is made to force the resulting filename to be an absolute
 
1895
 * path. If the first element is a relative path, the result will
 
1896
 * be a relative path. 
 
1897
 * 
 
1898
 * Return value: a newly-allocated string that must be freed with g_free().
 
1899
 **/
 
1900
gchar *
 
1901
g_build_filename (const gchar *first_element, 
 
1902
                  ...)
 
1903
{
 
1904
  gchar *str;
 
1905
  va_list args;
 
1906
 
 
1907
  va_start (args, first_element);
 
1908
#ifndef G_OS_WIN32
 
1909
  str = g_build_path_va (G_DIR_SEPARATOR_S, first_element, &args, NULL);
 
1910
#else
 
1911
  str = g_build_pathname_va (first_element, &args, NULL);
 
1912
#endif
 
1913
  va_end (args);
 
1914
 
 
1915
  return str;
 
1916
}
 
1917
 
 
1918
#define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
 
1919
#define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
 
1920
#define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
 
1921
#define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
 
1922
#define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
 
1923
#define EXABYTE_FACTOR  (PETABYTE_FACTOR * KILOBYTE_FACTOR)
 
1924
 
 
1925
#define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
 
1926
#define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
 
1927
#define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
 
1928
#define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
 
1929
#define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
 
1930
#define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
 
1931
 
 
1932
/**
 
1933
 * g_format_size:
 
1934
 * @size: a size in bytes
 
1935
 *
 
1936
 * Formats a size (for example the size of a file) into a human readable
 
1937
 * string.  Sizes are rounded to the nearest size prefix (kB, MB, GB)
 
1938
 * and are displayed rounded to the nearest tenth. E.g. the file size
 
1939
 * 3292528 bytes will be converted into the string "3.2 MB".
 
1940
 *
 
1941
 * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
 
1942
 *
 
1943
 * This string should be freed with g_free() when not needed any longer.
 
1944
 *
 
1945
 * See g_format_size_full() for more options about how the size might be
 
1946
 * formatted.
 
1947
 *
 
1948
 * Returns: a newly-allocated formatted string containing a human readable
 
1949
 *          file size.
 
1950
 *
 
1951
 * Since: 2.30
 
1952
 **/
 
1953
gchar *
 
1954
g_format_size (guint64 size)
 
1955
{
 
1956
  return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
 
1957
}
 
1958
 
 
1959
/**
 
1960
 * g_format_size_full:
 
1961
 * @size: a size in bytes
 
1962
 * @flags: #GFormatSizeFlags to modify the output
 
1963
 *
 
1964
 * Formats a size.
 
1965
 *
 
1966
 * This function is similar to g_format_size() but allows for flags that
 
1967
 * modify the output.  See #GFormatSizeFlags.
 
1968
 *
 
1969
 * Returns: a newly-allocated formatted string containing a human
 
1970
 *          readable file size.
 
1971
 *
 
1972
 * Since: 2.30
 
1973
 **/
 
1974
/**
 
1975
 * GFormatSizeFlags:
 
1976
 * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
 
1977
 * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
 
1978
 *                             of the returned string.  For example,
 
1979
 *                             "45.6 kB (45,612 bytes)".
 
1980
 * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
 
1981
 *                           suffixes.  IEC units should only be used
 
1982
 *                           for reporting things with a strong "power
 
1983
 *                           of 2" basis, like RAM sizes or RAID stripe
 
1984
 *                           sizes.  Network and storage sizes should
 
1985
 *                           be reported in the normal SI units.
 
1986
 *
 
1987
 * Flags to modify the format of the string returned by
 
1988
 * g_format_size_full().
 
1989
 **/
 
1990
gchar *
 
1991
g_format_size_full (guint64          size,
 
1992
                    GFormatSizeFlags flags)
 
1993
{
 
1994
  GString *string;
 
1995
 
 
1996
  string = g_string_new (NULL);
 
1997
 
 
1998
  if (flags & G_FORMAT_SIZE_IEC_UNITS)
 
1999
    {
 
2000
      if (size < KIBIBYTE_FACTOR)
 
2001
        {
 
2002
          g_string_printf (string,
 
2003
                           g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
 
2004
                           (guint) size);
 
2005
          flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
 
2006
        }
 
2007
 
 
2008
      else if (size < MEBIBYTE_FACTOR)
 
2009
        g_string_printf (string, _("%.1f KiB"), (gdouble) size / (gdouble) KIBIBYTE_FACTOR);
 
2010
 
 
2011
      else if (size < GIBIBYTE_FACTOR)
 
2012
        g_string_printf (string, _("%.1f MiB"), (gdouble) size / (gdouble) MEBIBYTE_FACTOR);
 
2013
 
 
2014
      else if (size < TEBIBYTE_FACTOR)
 
2015
        g_string_printf (string, _("%.1f GiB"), (gdouble) size / (gdouble) GIBIBYTE_FACTOR);
 
2016
 
 
2017
      else if (size < PEBIBYTE_FACTOR)
 
2018
        g_string_printf (string, _("%.1f TiB"), (gdouble) size / (gdouble) TEBIBYTE_FACTOR);
 
2019
 
 
2020
      else if (size < EXBIBYTE_FACTOR)
 
2021
        g_string_printf (string, _("%.1f PiB"), (gdouble) size / (gdouble) PEBIBYTE_FACTOR);
 
2022
 
 
2023
      else
 
2024
        g_string_printf (string, _("%.1f EiB"), (gdouble) size / (gdouble) EXBIBYTE_FACTOR);
 
2025
    }
 
2026
  else
 
2027
    {
 
2028
      if (size < KILOBYTE_FACTOR)
 
2029
        {
 
2030
          g_string_printf (string,
 
2031
                           g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
 
2032
                           (guint) size);
 
2033
          flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
 
2034
        }
 
2035
 
 
2036
      else if (size < MEGABYTE_FACTOR)
 
2037
        g_string_printf (string, _("%.1f kB"), (gdouble) size / (gdouble) KILOBYTE_FACTOR);
 
2038
 
 
2039
      else if (size < GIGABYTE_FACTOR)
 
2040
        g_string_printf (string, _("%.1f MB"), (gdouble) size / (gdouble) MEGABYTE_FACTOR);
 
2041
 
 
2042
      else if (size < TERABYTE_FACTOR)
 
2043
        g_string_printf (string, _("%.1f GB"), (gdouble) size / (gdouble) GIGABYTE_FACTOR);
 
2044
 
 
2045
      else if (size < PETABYTE_FACTOR)
 
2046
        g_string_printf (string, _("%.1f TB"), (gdouble) size / (gdouble) TERABYTE_FACTOR);
 
2047
 
 
2048
      else if (size < EXABYTE_FACTOR)
 
2049
        g_string_printf (string, _("%.1f PB"), (gdouble) size / (gdouble) PETABYTE_FACTOR);
 
2050
 
 
2051
      else
 
2052
        g_string_printf (string, _("%.1f EB"), (gdouble) size / (gdouble) EXABYTE_FACTOR);
 
2053
    }
 
2054
 
 
2055
  if (flags & G_FORMAT_SIZE_LONG_FORMAT)
 
2056
    {
 
2057
      /* First problem: we need to use the number of bytes to decide on
 
2058
       * the plural form that is used for display, but the number of
 
2059
       * bytes potentially exceeds the size of a guint (which is what
 
2060
       * ngettext() takes).
 
2061
       *
 
2062
       * From a pragmatic standpoint, it seems that all known languages
 
2063
       * base plural forms on one or both of the following:
 
2064
       *
 
2065
       *   - the lowest digits of the number
 
2066
       *
 
2067
       *   - if the number if greater than some small value
 
2068
       *
 
2069
       * Here's how we fake it:  Draw an arbitrary line at one thousand.
 
2070
       * If the number is below that, then fine.  If it is above it,
 
2071
       * then we take the modulus of the number by one thousand (in
 
2072
       * order to keep the lowest digits) and add one thousand to that
 
2073
       * (in order to ensure that 1001 is not treated the same as 1).
 
2074
       */
 
2075
      guint plural_form = size < 1000 ? size : size % 1000 + 1000;
 
2076
 
 
2077
      /* Second problem: we need to translate the string "%u byte" and
 
2078
       * "%u bytes" for pluralisation, but the correct number format to
 
2079
       * use for a gsize is different depending on which architecture
 
2080
       * we're on.
 
2081
       *
 
2082
       * Solution: format the number separately and use "%s bytes" on
 
2083
       * all platforms.
 
2084
       */
 
2085
      const gchar *translated_format;
 
2086
      gchar *formatted_number;
 
2087
 
 
2088
      /* Translators: the %s in "%s bytes" will always be replaced by a number. */
 
2089
      translated_format = g_dngettext(GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
 
2090
 
 
2091
      /* XXX: Windows doesn't support the "'" format modifier, so we
 
2092
       * must not use it there.  Instead, just display the number
 
2093
       * without separation.  Bug #655336 is open until a solution is
 
2094
       * found.
 
2095
       */
 
2096
#ifndef G_OS_WIN32
 
2097
      formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
 
2098
#else
 
2099
      formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
 
2100
#endif
 
2101
 
 
2102
      g_string_append (string, " (");
 
2103
      g_string_append_printf (string, translated_format, formatted_number);
 
2104
      g_free (formatted_number);
 
2105
      g_string_append (string, ")");
 
2106
    }
 
2107
 
 
2108
  return g_string_free (string, FALSE);
 
2109
}
 
2110
 
 
2111
/**
 
2112
 * g_format_size_for_display:
 
2113
 * @size: a size in bytes.
 
2114
 * 
 
2115
 * Formats a size (for example the size of a file) into a human readable string.
 
2116
 * Sizes are rounded to the nearest size prefix (KB, MB, GB) and are displayed 
 
2117
 * rounded to the nearest  tenth. E.g. the file size 3292528 bytes will be
 
2118
 * converted into the string "3.1 MB".
 
2119
 *
 
2120
 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
 
2121
 *
 
2122
 * This string should be freed with g_free() when not needed any longer.
 
2123
 *
 
2124
 * Returns: a newly-allocated formatted string containing a human readable
 
2125
 *          file size.
 
2126
 *
 
2127
 * Deprecated:2.30: This function is broken due to its use of SI
 
2128
 *                  suffixes to denote IEC units.  Use g_format_size()
 
2129
 *                  instead.
 
2130
 * Since: 2.16
 
2131
 **/
 
2132
char *
 
2133
g_format_size_for_display (goffset size)
 
2134
{
 
2135
  if (size < (goffset) KIBIBYTE_FACTOR)
 
2136
    return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
 
2137
  else
 
2138
    {
 
2139
      gdouble displayed_size;
 
2140
      
 
2141
      if (size < (goffset) MEBIBYTE_FACTOR)
 
2142
        {
 
2143
          displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
 
2144
          return g_strdup_printf (_("%.1f KB"), displayed_size);
 
2145
        }
 
2146
      else if (size < (goffset) GIBIBYTE_FACTOR)
 
2147
        {
 
2148
          displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
 
2149
          return g_strdup_printf (_("%.1f MB"), displayed_size);
 
2150
        }
 
2151
      else if (size < (goffset) TEBIBYTE_FACTOR)
 
2152
        {
 
2153
          displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
 
2154
          return g_strdup_printf (_("%.1f GB"), displayed_size);
 
2155
        }
 
2156
      else if (size < (goffset) PEBIBYTE_FACTOR)
 
2157
        {
 
2158
          displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
 
2159
          return g_strdup_printf (_("%.1f TB"), displayed_size);
 
2160
        }
 
2161
      else if (size < (goffset) EXBIBYTE_FACTOR)
 
2162
        {
 
2163
          displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
 
2164
          return g_strdup_printf (_("%.1f PB"), displayed_size);
 
2165
        }
 
2166
      else
 
2167
        {
 
2168
          displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
 
2169
          return g_strdup_printf (_("%.1f EB"), displayed_size);
 
2170
        }
 
2171
    }
 
2172
}
 
2173
 
 
2174
 
 
2175
/**
 
2176
 * g_file_read_link:
 
2177
 * @filename: the symbolic link
 
2178
 * @error: return location for a #GError
 
2179
 *
 
2180
 * Reads the contents of the symbolic link @filename like the POSIX
 
2181
 * readlink() function.  The returned string is in the encoding used
 
2182
 * for filenames. Use g_filename_to_utf8() to convert it to UTF-8.
 
2183
 *
 
2184
 * Returns: A newly-allocated string with the contents of the symbolic link, 
 
2185
 *          or %NULL if an error occurred.
 
2186
 *
 
2187
 * Since: 2.4
 
2188
 */
 
2189
gchar *
 
2190
g_file_read_link (const gchar  *filename,
 
2191
                  GError      **error)
 
2192
{
 
2193
#ifdef HAVE_READLINK
 
2194
  gchar *buffer;
 
2195
  guint size;
 
2196
  gint read_size;    
 
2197
  
 
2198
  size = 256; 
 
2199
  buffer = g_malloc (size);
 
2200
  
 
2201
  while (TRUE) 
 
2202
    {
 
2203
      read_size = readlink (filename, buffer, size);
 
2204
      if (read_size < 0) {
 
2205
        int save_errno = errno;
 
2206
        gchar *display_filename = g_filename_display_name (filename);
 
2207
 
 
2208
        g_free (buffer);
 
2209
        g_set_error (error,
 
2210
                     G_FILE_ERROR,
 
2211
                     g_file_error_from_errno (save_errno),
 
2212
                     _("Failed to read the symbolic link '%s': %s"),
 
2213
                     display_filename, 
 
2214
                     g_strerror (save_errno));
 
2215
        g_free (display_filename);
 
2216
        
 
2217
        return NULL;
 
2218
      }
 
2219
    
 
2220
      if (read_size < size) 
 
2221
        {
 
2222
          buffer[read_size] = 0;
 
2223
          return buffer;
 
2224
        }
 
2225
      
 
2226
      size *= 2;
 
2227
      buffer = g_realloc (buffer, size);
 
2228
    }
 
2229
#else
 
2230
  g_set_error_literal (error,
 
2231
                       G_FILE_ERROR,
 
2232
                       G_FILE_ERROR_INVAL,
 
2233
                       _("Symbolic links not supported"));
 
2234
        
 
2235
  return NULL;
 
2236
#endif
 
2237
}
 
2238
 
 
2239
/* NOTE : Keep this part last to ensure nothing in this file uses the
 
2240
 * below binary compatibility versions.
 
2241
 */
 
2242
#if defined (G_OS_WIN32) && !defined (_WIN64)
 
2243
 
 
2244
/* Binary compatibility versions. Will be called by code compiled
 
2245
 * against quite old (pre-2.8, I think) headers only, not from more
 
2246
 * recently compiled code.
 
2247
 */
 
2248
 
 
2249
#undef g_file_test
 
2250
 
 
2251
gboolean
 
2252
g_file_test (const gchar *filename,
 
2253
             GFileTest    test)
 
2254
{
 
2255
  gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, NULL);
 
2256
  gboolean retval;
 
2257
 
 
2258
  if (utf8_filename == NULL)
 
2259
    return FALSE;
 
2260
 
 
2261
  retval = g_file_test_utf8 (utf8_filename, test);
 
2262
 
 
2263
  g_free (utf8_filename);
 
2264
 
 
2265
  return retval;
 
2266
}
 
2267
 
 
2268
#undef g_file_get_contents
 
2269
 
 
2270
gboolean
 
2271
g_file_get_contents (const gchar  *filename,
 
2272
                     gchar       **contents,
 
2273
                     gsize        *length,
 
2274
                     GError      **error)
 
2275
{
 
2276
  gchar *utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
 
2277
  gboolean retval;
 
2278
 
 
2279
  if (utf8_filename == NULL)
 
2280
    return FALSE;
 
2281
 
 
2282
  retval = g_file_get_contents_utf8 (utf8_filename, contents, length, error);
 
2283
 
 
2284
  g_free (utf8_filename);
 
2285
 
 
2286
  return retval;
 
2287
}
 
2288
 
 
2289
#undef g_mkstemp
 
2290
 
 
2291
gint
 
2292
g_mkstemp (gchar *tmpl)
 
2293
{
 
2294
  /* This is the backward compatibility system codepage version,
 
2295
   * thus use normal open().
 
2296
   */
 
2297
  return get_tmp_file (tmpl, (GTmpFileCallback) open,
 
2298
                       O_RDWR | O_CREAT | O_EXCL, 0600);
 
2299
}
 
2300
 
 
2301
#undef g_file_open_tmp
 
2302
 
 
2303
gint
 
2304
g_file_open_tmp (const gchar  *tmpl,
 
2305
                 gchar       **name_used,
 
2306
                 GError      **error)
 
2307
{
 
2308
  gchar *utf8_tmpl = g_locale_to_utf8 (tmpl, -1, NULL, NULL, error);
 
2309
  gchar *utf8_name_used;
 
2310
  gint retval;
 
2311
 
 
2312
  if (utf8_tmpl == NULL)
 
2313
    return -1;
 
2314
 
 
2315
  retval = g_file_open_tmp_utf8 (utf8_tmpl, &utf8_name_used, error);
 
2316
  
 
2317
  if (retval == -1)
 
2318
    return -1;
 
2319
 
 
2320
  if (name_used)
 
2321
    *name_used = g_locale_from_utf8 (utf8_name_used, -1, NULL, NULL, NULL);
 
2322
 
 
2323
  g_free (utf8_name_used);
 
2324
 
 
2325
  return retval;
 
2326
}
 
2327
 
 
2328
#endif