static char rcsid[] = "$Id: safeopen.c,v 1.6 2006/04/09 07:37:05 hurtta Exp $";

/******************************************************************************
 *  The Elm (ME+) Mail System  -  $Revision: 1.6 $   $State: Exp $
 *
 *  Modified by: Kari Hurtta <hurtta+elm@posti.FMI.FI> 
 *                           (was hurtta+elm@ozone.FMI.FI)
 *
 *  Initially written by: Zoltan Hidvegi <hzoli@cs.elte.hu>
 *****************************************************************************/

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

#include "headers.h"

FILE *safeopen(name)
     char *name;
{
    FILE *fp;
    int fd = open(name, O_WRONLY | O_CREAT | O_EXCL, 0600);

    if (fd < 0 &&
	(unlink(name) ||
	 (fd = open(name, O_WRONLY | O_CREAT | O_EXCL, 0600)) < 0))
	return NULL;

    if (! (fp = fdopen(fd, "w"))) {
      close(fd);
      unlink(name);
    }
    return fp;
}

FILE *safeopen_rdwr(name)
     char *name;
{
    FILE *fp;
    int fd = open(name, O_RDWR | O_CREAT | O_EXCL, 0600);

    if (fd < 0 &&
	(unlink(name) ||
	 (fd = open(name, O_RDWR | O_CREAT | O_EXCL, 0600)) < 0))
	return NULL;

    if (! (fp = fdopen(fd, "w+"))) {
      close(fd);
      unlink(name);
    }
    return fp;
}

/*
 * Local Variables:
 *  mode:c
 *  c-basic-offset:4
 *  buffer-file-coding-system: iso-8859-1
 * End:
 */


syntax highlighted by Code2HTML, v. 0.9.1