/* mr_file.c
 *
 * $Id$
 *
 * File management for mondo
 * Code (c)2006 Bruno Cornec <bruno@mondorescue.org>
 *   
 * Provided under the GPLv2
 */


#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>

#include "mr_err.h"
#include "mr_msg.h"

/*open and read file: each call must be coupled with mr_conf_close
  function: return 0 if success*/
FILE *mr_fopen(const char *path, const char *mode) {
	FILE *fd = NULL;

	if ((fd = fopen(path, mode)) == NULL) {
		mr_msg(0,"Unable to open %s",path);
		mr_exit(-1,"Exiting");
	}
	return(fd);
}

void mr_fprintf(FILE *fd, const char *fmt, ...) {
	
	va_list args;

	if (fd == NULL) {
		mr_log_exit(-1,"fd is NULL.\nShould NOT happen.\nExiting");
	}
	va_start(args,fmt);
	if (vfprintf(fd, fmt, args) < 0) {
		mr_msg(0,"Unable to print '%s'",args);
	}
	va_end(args);
}

void mr_fclose(FILE *fd) {

	if (fd == NULL) {
		mr_log_exit(-1,"fd is NULL.\nShould NOT happen.\nExiting");
	}
	if (fclose(fd) < 0) {
		mr_msg(0,"Unable to close fd");
	}
	fd = NULL;
}

void mr_mkdir(const char *pathname, mode_t mode) {

	if (mkdir(pathname,mode) != 0) {
		mr_msg("Unable to create directory %s",pathname);
		mr_exit(-1,"Exiting");
	}
}
