1 /*
2 Copyright (c) 1990 The Regents of the University of California.
3 All rights reserved.
4
5 Redistribution and use in source and binary forms are permitted
6 provided that the above copyright notice and this paragraph are
7 duplicated in all such forms and that any documentation,
8 and/or other materials related to such
9 distribution and use acknowledge that the software was developed
10 by the University of California, Berkeley. The name of the
11 University may not be used to endorse or promote products derived
12 from this software without specific prior written permission.
13 THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14 IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16 */
17 /*
18 FUNCTION
19 <<tmpfile>>---create a temporary file
20
21 INDEX
22 tmpfile
23 INDEX
24 _tmpfile_r
25
26 SYNOPSIS
27 #include <stdio.h>
28 FILE *tmpfile(void);
29
30 FILE *_tmpfile_r(struct _reent *<[reent]>);
31
32 DESCRIPTION
33 Create a temporary file (a file which will be deleted automatically),
34 using a name generated by <<tmpnam>>. The temporary file is opened with
35 the mode <<"wb+">>, permitting you to read and write anywhere in it
36 as a binary file (without any data transformations the host system may
37 perform for text files).
38
39 The alternate function <<_tmpfile_r>> is a reentrant version. The
40 argument <[reent]> is a pointer to a reentrancy structure.
41
42 RETURNS
43 <<tmpfile>> normally returns a pointer to the temporary file. If no
44 temporary file could be created, the result is NULL, and <<errno>>
45 records the reason for failure.
46
47 PORTABILITY
48 Both ANSI C and the System V Interface Definition (Issue 2) require
49 <<tmpfile>>.
50
51 Supporting OS subroutines required: <<close>>, <<fstat>>, <<getpid>>,
52 <<isatty>>, <<lseek>>, <<open>>, <<read>>, <<sbrk>>, <<write>>.
53
54 <<tmpfile>> also requires the global pointer <<environ>>.
55 */
56
57 #define _DEFAULT_SOURCE
58 #include <_ansi.h>
59 #include <stdio.h>
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <unistd.h>
63 #include <sys/stat.h>
64
65 #ifndef O_BINARY
66 # define O_BINARY 0
67 #endif
68
69 FILE *
tmpfile(void)70 tmpfile (void)
71 {
72 FILE *fp;
73 int e;
74 char *f;
75 char buf[L_tmpnam];
76 int fd;
77
78 do
79 {
80 if ((f = tmpnam ( buf)) == NULL)
81 return NULL;
82 fd = open (f, O_RDWR | O_CREAT | O_EXCL | O_BINARY,
83 S_IRUSR | S_IWUSR);
84 }
85 while (fd < 0 && _REENT_ERRNO(ptr) == EEXIST);
86 if (fd < 0)
87 return NULL;
88 fp = fdopen ( fd, "wb+");
89 e = _REENT_ERRNO(ptr);
90 if (!fp)
91 close (fd);
92 (void) remove (f);
93 _REENT_ERRNO(ptr) = e;
94 return fp;
95 }
96