modules/libmar/src/mar_extract.c

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/modules/libmar/src/mar_extract.c	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,83 @@
     1.4 +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
     1.5 +/* vim:set ts=2 sw=2 sts=2 et cindent: */
     1.6 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.7 + * License, v. 2.0. If a copy of the MPL was not distributed with this
     1.8 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.9 +
    1.10 +#include <sys/types.h>
    1.11 +#include <sys/stat.h>
    1.12 +#include <fcntl.h>
    1.13 +#include <string.h>
    1.14 +#include <stdlib.h>
    1.15 +#include "mar_private.h"
    1.16 +#include "mar.h"
    1.17 +
    1.18 +#ifdef XP_WIN
    1.19 +#include <io.h>
    1.20 +#include <direct.h>
    1.21 +#endif
    1.22 +
    1.23 +/* Ensure that the directory containing this file exists */
    1.24 +static int mar_ensure_parent_dir(const char *path)
    1.25 +{
    1.26 +  char *slash = strrchr(path, '/');
    1.27 +  if (slash)
    1.28 +  {
    1.29 +    *slash = '\0';
    1.30 +    mar_ensure_parent_dir(path);
    1.31 +#ifdef XP_WIN
    1.32 +    _mkdir(path);
    1.33 +#else
    1.34 +    mkdir(path, 0755);
    1.35 +#endif
    1.36 +    *slash = '/';
    1.37 +  }
    1.38 +  return 0;
    1.39 +}
    1.40 +
    1.41 +static int mar_test_callback(MarFile *mar, const MarItem *item, void *unused) {
    1.42 +  FILE *fp;
    1.43 +  char buf[BLOCKSIZE];
    1.44 +  int fd, len, offset = 0;
    1.45 +
    1.46 +  if (mar_ensure_parent_dir(item->name))
    1.47 +    return -1;
    1.48 +
    1.49 +#ifdef XP_WIN
    1.50 +  fd = _open(item->name, _O_BINARY|_O_CREAT|_O_TRUNC|_O_WRONLY, item->flags);
    1.51 +#else
    1.52 +  fd = creat(item->name, item->flags);
    1.53 +#endif
    1.54 +  if (fd == -1) {
    1.55 +    fprintf(stderr, "ERROR: could not create file in mar_test_callback()\n");
    1.56 +    perror(item->name);
    1.57 +    return -1;
    1.58 +  }
    1.59 +
    1.60 +  fp = fdopen(fd, "wb");
    1.61 +  if (!fp)
    1.62 +    return -1;
    1.63 +
    1.64 +  while ((len = mar_read(mar, item, offset, buf, sizeof(buf))) > 0) {
    1.65 +    if (fwrite(buf, len, 1, fp) != 1)
    1.66 +      break;
    1.67 +    offset += len;
    1.68 +  }
    1.69 +
    1.70 +  fclose(fp);
    1.71 +  return len == 0 ? 0 : -1;
    1.72 +}
    1.73 +
    1.74 +int mar_extract(const char *path) {
    1.75 +  MarFile *mar;
    1.76 +  int rv;
    1.77 +
    1.78 +  mar = mar_open(path);
    1.79 +  if (!mar)
    1.80 +    return -1;
    1.81 +
    1.82 +  rv = mar_enum_items(mar, mar_test_callback, NULL);
    1.83 +
    1.84 +  mar_close(mar);
    1.85 +  return rv;
    1.86 +}

mercurial