2 * Copyright (c) 2012 Dag-Erling Smørgrav
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote
14 * products derived from this software without specific prior written
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * $Id: t_file.c 648 2013-03-05 17:54:27Z des $
45 #include "openpam_asprintf.h"
49 static struct t_file *tflist;
55 t_fopen(const char *filename)
60 if ((tf = calloc(sizeof *tf, 1)) == NULL)
61 err(1, "%s(): calloc()", __func__);
63 if ((tf->name = strdup(filename)) == NULL)
64 err(1, "%s(): strdup()", __func__);
66 asprintf(&tf->name, "%s.%lu.%p.tmp",
67 t_progname, (unsigned long)getpid(), (void *)tf);
69 err(1, "%s(): asprintf()", __func__);
71 if ((fd = open(tf->name, O_RDWR|O_CREAT|O_TRUNC, 0600)) < 0)
72 err(1, "%s(): %s", __func__, tf->name);
73 if ((tf->file = fdopen(fd, "r+")) == NULL)
74 err(1, "%s(): fdopen()", __func__);
75 if ((tf->next = tflist) != NULL)
82 * Write text to the temp file.
85 t_fprintf(struct t_file *tf, const char *fmt, ...)
91 len = vfprintf(tf->file, fmt, ap);
94 err(1, "%s(): vfprintf()", __func__);
99 * Rewind the temp file.
102 t_frewind(struct t_file *tf)
108 err(1, "%s(): rewind()", __func__);
112 * Return non-zero if an error occurred.
115 t_ferror(struct t_file *tf)
118 return (ferror(tf->file));
122 * Return non-zero if the end of the file was reached.
125 t_feof(struct t_file *tf)
128 return (feof(tf->file));
135 t_fclose(struct t_file *tf)
141 tf->prev->next = tf->next;
143 tf->next->prev = tf->prev;
145 if (unlink(tf->name) < 0)
146 warn("%s(): unlink()", __func__);
152 * atexit() function to close all remaining files.