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.
44 static struct temp_dir *temp_dir;
51 temp_dir = create_temp_dir ("pspp", NULL, true);
57 struct hmapx_node *node;
60 cleanup_temp_dir (temp_dir);
62 HMAPX_FOR_EACH (fn, node, &map)
71 create_temp_file (void)
85 file_name = xasprintf ("%s/%d", temp_dir->dir_name, idx++);
86 register_temp_file (temp_dir, file_name);
87 stream = fopen_temp (file_name, "wb+");
89 unregister_temp_file (temp_dir, file_name);
91 setvbuf (stream, NULL, _IOFBF, 65536);
93 hmapx_insert (&map, file_name, hash_pointer (stream, 0));
98 /* Closes and removes a temporary file created by create_temp_file(). */
100 close_temp_file (FILE *file)
104 struct hmapx_node *node = hmapx_first_with_hash (&map, hash_pointer (file, 0));
105 char *fn = node->data;
107 cleanup_temp_file (temp_dir, fn);
108 hmapx_delete (&map, node);