/* file.hh - files with fd
 * Copyright 2003 Bas Wijnen <wijnen@debian.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "file.hh"
#include "error.hh"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

namespace shevek
{
  void file::open (std::string name, bool read, bool write)
  {
    if (!read && !write)
      shevek_error ("unable to open file: not reading and not writing");
    int flags = read ? (write ? O_RDWR : O_RDONLY) : O_WRONLY;
    // NOCTTY is probably not usually doing anything, but it's good if it does.
    int filedes = ::open (name.c_str (), flags | O_NOCTTY);
    if (filedes < 0)
      shevek_error_errno ("unable to open file");
    set_fd (filedes);
  }

  file::file (Glib::RefPtr <Glib::MainContext> main)
    : fd (-1, main)
  {
    set_eof (sigc::mem_fun (*this, &file::close) );
  }

  void file::close ()
  {
    if (get_fd () >= 0)
      ::close (get_fd () );
  }

  file::~file ()
  {
    close ();
  }

  Glib::RefPtr <file> file::create (Glib::RefPtr <Glib::MainContext> main)
  {
    return Glib::RefPtr <file> (new file (main) );
  }
}
