/*
 * This file is part of the Poliqarp suite.
 * 
 * Copyright (C) 2008-2009 by Instytut Podstaw Informatyki Polskiej
 * Akademii Nauk (IPI PAN; Institute of Computer Science, Polish
 * Academy of Sciences; cf. www.ipipan.waw.pl).  All rights reserved.
 * 
 * This file may be distributed and/or modified under the terms of the
 * GNU General Public License version 2 as published by the Free Software
 * Foundation and appearing in the file gpl.txt included in the packaging
 * of this file.  (See http://www.gnu.org/licenses/translations.html for
 * unofficial translations.)
 * 
 * A commercial license is available from IPI PAN (contact
 * Michal.Ciesiolka@ipipan.waw.pl or ipi@ipipan.waw.pl for more
 * information).  Licensees holding a valid commercial license from IPI
 * PAN may use this file in accordance with that license.
 * 
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
 * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.
 */

#include <poliqarp-config.h>

#include <assert.h>
#include <unistd.h>

#include <bp/common.h>
#include <bp/io.h>

FILE *bp_open(const string_t path, const char *mode)
{
   FILE *fp = fopen(string_str(path), mode);
   if (fp == NULL)
      bp_system_error("unable to open %s", string_str(path));
   return fp;
}

void bp_close(FILE *fp)
{
   int rc;
   assert(fp != NULL);
   rc = fclose(fp);
   if (rc != 0)
     bp_system_error("unable to close a file");
}

void bp_truncate(FILE *fp, off64_t length)
{
   int rc, fd;
   assert(fp != NULL);
   rc = fflush(fp);
   if (rc != 0)
      bp_system_error("write error");
   fd = fileno(fp);
   assert(fd != -1);
   rc = ftruncate(fd, length);
   if (rc != 0)
      bp_system_error("unable to truncate a file");
}

void bp_try_unlink(const string_t path)
{
   unlink(string_str(path));
}

void bp_unlink(const string_t path)
{
   int rc;
   rc = unlink(string_str(path));
   if (rc != 0)
      bp_system_error("unable to remove %s", string_str(path));
}

void bp_rename(const string_t old, const string_t new)
{
   int rc;
   rc = rename(string_str(old), string_str(new));
   if (rc != 0)
      bp_system_error("unable to rename %s to %s", string_str(old), string_str(new));
}

size_t bp_read(FILE *stream, void *ptr, size_t size, size_t nmemb)
{
   size_t res = fread(ptr, size, nmemb, stream);
   if (ferror(stream))
      bp_system_error("read error");
   return res;
}

size_t bp_write(FILE *stream, void *ptr, size_t size, size_t nmemb)
{
   size_t res = fwrite(ptr, size, nmemb, stream);
   if (ferror(stream))
      bp_system_error("write error");
   return res;
}
