/* file-contents.c:
 *
 ****************************************************************
 * Copyright (C) 2003 Tom Lord
 *
 * See the file "COPYING" for further information about
 * the copyright and warranty status of this work.
 */


#include "hackerlab/bugs/exception.h"
#include "hackerlab/vu/safe.h"
#include "hackerlab/fs/file-names.h"
#include "libfsutils/tmp-files.h"
#include "libfsutils/file-contents.h"



t_uchar *
file_contents (t_uchar const * path)
{
  int in_fd;
  t_uchar * buf = 0;
  size_t len = 0;

  in_fd = safe_open ((t_uchar *)path, O_RDONLY, 0);
  safe_file_to_string (&buf, &len, in_fd);
  safe_close (in_fd);

  buf = lim_realloc (0, buf, len + 1);
  buf[len] = 0;
  return buf;
}

void
file_set_contents (t_uchar const * path, t_uchar const *contents)
{
  t_uchar * dir = file_name_directory_file (0, (t_uchar *)path);
  t_uchar * tmp_name = talloc_tmp_file_name (talloc_context, dir, ",,file-contents");
  int out_fd = safe_open (tmp_name, O_WRONLY | O_CREAT | O_EXCL, 0666);
  safe_printfmt (out_fd, "%s", contents);
  safe_close (out_fd);
  
  safe_rename (tmp_name, (t_uchar *)path);
  talloc_free (tmp_name);
  lim_free (0, dir);
}

t_uchar *
fd_contents (int in_fd)
{
  t_uchar * buf = 0;
  size_t len = 0;

  safe_file_to_string (&buf, &len, in_fd);

  buf = lim_realloc (0, buf, len + 1);
  buf[len] = 0;
  return buf;
}

/**
 * \brief return the content of a file, broken at newlines.
 * \return rel_table
 */
rel_table
file_lines (t_uchar const *path)
{
    t_uchar *contents=file_contents ((t_uchar *)path);
    rel_table result = rel_nl_split (contents);
    lim_free (0, contents);
    return result;
}

/**
 * \brief return the number of lines in the file
 */
int
file_line_count (t_uchar const *path)
{
    rel_table lines = file_lines (path);
    int result = rel_n_records (lines);
    rel_free_table (lines);
    return result;
}



/* tag: Tom Lord Thu May 22 19:46:48 2003 (file-contents.c)
 */


syntax highlighted by Code2HTML, v. 0.9.1