1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2010, 2011 Free Software Foundation, Inc.
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.
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.
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/>. */
17 /* Functions for temporary files that honor $TMPDIR. */
21 #include "libpspp/temp-file.h"
22 #include "libpspp/hmapx.h"
23 #include "libpspp/hash-functions.h"
27 #include "gl/clean-temp.h"
28 #include "gl/xvasprintf.h"
30 /* Creates and returns a new temporary file that will be removed automatically
31 when the process exits. The file is opened in mode "wb+". To close the
32 file before the process exits, use close_temp_file() to ensure that it gets
35 Returns NULL if creating the temporary file fails.
37 This is similar to tmpfile(), except:
39 - It honors the $TMPDIR environment variable.
43 static void cleanup (void);
45 static struct temp_dir *temp_dir;
52 temp_dir = create_temp_dir ("pspp", NULL, true);
74 return temp_dir->dir_name;
82 struct hmapx_node *node;
85 cleanup_temp_dir (temp_dir);
87 HMAPX_FOR_EACH (fn, node, &map)
96 create_temp_file (void)
103 if (temp_dir == NULL)
106 file_name = xasprintf ("%s/%d", temp_dir->dir_name, idx++);
107 register_temp_file (temp_dir, file_name);
108 stream = fopen_temp (file_name, "wb+");
110 unregister_temp_file (temp_dir, file_name);
112 setvbuf (stream, NULL, _IOFBF, 65536);
114 hmapx_insert (&map, file_name, hash_pointer (stream, 0));
119 /* Closes and removes a temporary file created by create_temp_file(). */
121 close_temp_file (FILE *file)
125 struct hmapx_node *node = hmapx_first_with_hash (&map, hash_pointer (file, 0));
126 char *fn = node->data;
128 cleanup_temp_file (temp_dir, fn);
129 hmapx_delete (&map, node);