/*
 *	fhist - file history and comparison tools
 *	Copyright (C) 2000, 2002 Peter Miller;
 *	All rights reserved.
 *
 *	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 2 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, write to the Free Software
 *	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
 *
 * MANIFEST: functions to check file accesses
 */

#include <ac/string.h>

#include <error_intl.h>
#include <fcheck.h>
#include <str.h>


FILE *
fopen_and_check(const char *filename, const char *mode)
{
    FILE	    *fp;

    if (!filename)
	return (strchr(mode, 'r') ? stdin : stdout);
    fp = fopen(filename, mode);
    if (!fp)
    {
	sub_context_ty	*scp;

	scp = sub_context_new();
	sub_errno_set(scp);
	sub_var_set_charstar(scp, "File_Name", filename);
	fatal_intl(scp, i18n("open \"$filename\": $errno"));
    }
    return fp;
}


void
fflush_and_check(FILE *fp, const char *filename)
{
    if (fflush(fp))
    {
	sub_context_ty	*scp;

	scp = sub_context_new();
	sub_errno_set(scp);
	sub_var_set_charstar(scp, "File_Name", filename);
	fatal_intl(scp, i18n("write \"$filename\": $errno"));
    }
}


void
fclose_and_check(FILE *fp, const char *filename)
{
    if (fp == stdout || fp == stdin)
	return;
    if (fclose(fp))
    {
	sub_context_ty	*scp;

	scp = sub_context_new();
	sub_errno_set(scp);
	sub_var_set_charstar(scp, "File_Name", filename);
	fatal_intl(scp, i18n("close \"$filename\": $errno"));
    }
}


void
fatal_with_filename(const char *filename, sub_context_ty *scp, const char *text)
{
    string_ty       *s;

    if (!scp)
	scp = sub_context_new();
    s = subst_intl(scp, (char *)text);
    sub_var_set_charstar(scp, "File_Name", filename);
    sub_var_set_string(scp, "MeSsaGe", s);
    str_free(s);
    fatal_intl(scp, i18n("$filename: $message"));
}


void
warning_last_line_unterminated(const char *filename)
{
    sub_context_ty  *scp;

    scp = sub_context_new();
    sub_var_set_charstar(scp, "File_Name", filename);
    error_intl(scp, i18n("$filename: warning: last line unterminated"));
    sub_context_delete(scp);
}


syntax highlighted by Code2HTML, v. 0.9.1