ffd5da7cef162dfdaef2ab20e66513b33b67b5ba
[pspp] / src / libpspp / temp-file.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2010, 2011 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 /* Functions for temporary files that honor $TMPDIR. */
18
19 #include <config.h>
20
21 #include "libpspp/temp-file.h"
22
23 #include <stdlib.h>
24
25 #include "gl/clean-temp.h"
26 #include "gl/xvasprintf.h"
27
28 /* Creates and returns a new temporary file that will be removed automatically
29    when the process exits.  The file is opened in mode "wb+".  To close the
30    file before the process exits, use close_temp_file() to ensure that it gets
31    deleted early.
32
33    Returns NULL if creating the temporary file fails.
34
35    This is similar to tmpfile(), except:
36
37      - It honors the $TMPDIR environment variable.
38
39      - The file will not be automatically deleted upon close.  You have to call
40        close_temp_file() if you want it to be deleted before the process exits.
41 */
42 FILE *
43 create_temp_file (void)
44 {
45   static int idx = 0;
46   static struct temp_dir *temp_dir;
47   char *file_name;
48   FILE *stream;
49
50   if (temp_dir == NULL)
51     {
52       temp_dir = create_temp_dir ("pspp", NULL, true);
53       if (temp_dir == NULL)
54         return NULL;
55     }
56
57   file_name = xasprintf ("%s/%d", temp_dir->dir_name, idx++);
58   stream = fopen_temp (file_name, "wb+");
59   if (stream != NULL)
60     setvbuf (stream, NULL, _IOFBF, 65536);
61   free (file_name);
62
63   return stream;
64 }
65
66 /* Closes and removes a temporary file created by create_temp_file(). */
67 void
68 close_temp_file (FILE *file)
69 {
70   if (file != NULL)
71     fclose_temp (file);
72 }