5 This file is part of the Public Domain C Library (PDCLib).
6 Permission is granted to use, modify, and / or redistribute at will.
17 #include <_PDCLIB_glue.h>
19 #include <sys/types.h>
24 extern struct _PDCLIB_file_t * _PDCLIB_filelist;
26 /* This is an example implementation of tmpfile() fit for use with POSIX
29 struct _PDCLIB_file_t * tmpfile( void )
32 /* This is the chosen way to get high-quality randomness. Replace as
35 FILE * randomsource = fopen( "/proc/sys/kernel/random/uuid", "rb" );
36 char filename[ L_tmpnam ];
38 if ( randomsource == NULL )
44 /* Get a filename candidate. What constitutes a valid filename and
45 where temporary files are usually located is platform-dependent,
46 which is one reason why this function is located in the platform
47 overlay. The other reason is that a *good* implementation should
48 use high-quality randomness instead of a pseudo-random sequence to
49 generate the filename candidate, which is *also* platform-dependent.
52 fscanf( randomsource, "%u", &random );
53 sprintf( filename, "/tmp/%u.tmp", random );
54 /* Check if file of this name exists. Note that fopen() is a very weak
55 check, which does not take e.g. access permissions into account
56 (file might exist but not readable). Replace with something more
59 fd = open( filename, O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR );
66 fclose( randomsource );
68 if ( ( rc = calloc( 1, sizeof( struct _PDCLIB_file_t ) + _PDCLIB_UNGETCBUFSIZE + L_tmpnam + BUFSIZ ) ) == NULL )
70 /* No memory to set up FILE structure */
74 rc->status = _PDCLIB_filemode( "wb+" ) | _IOLBF | _PDCLIB_DELONCLOSE;
76 rc->ungetbuf = (unsigned char *)rc + sizeof( struct _PDCLIB_file_t );
77 rc->filename = (char *)rc->ungetbuf + _PDCLIB_UNGETCBUFSIZE;
78 rc->buffer = rc->filename + L_tmpnam;
79 strcpy( rc->filename, filename );
83 rc->next = _PDCLIB_filelist;
84 _PDCLIB_filelist = rc;
91 #include <_PDCLIB_test.h>
97 char filename[ L_tmpnam ];
99 TESTCASE( ( fh = tmpfile() ) != NULL );
100 TESTCASE( fputc( 'x', fh ) == 'x' );
101 /* Checking that file is actually there */
102 TESTCASE_NOREG( strcpy( filename, fh->filename ) == filename );
103 TESTCASE_NOREG( ( fhtest = fopen( filename, "r" ) ) != NULL );
104 TESTCASE_NOREG( fclose( fhtest ) == 0 );
105 /* Closing tmpfile */
106 TESTCASE( fclose( fh ) == 0 );
107 /* Checking that file was deleted */
108 TESTCASE_NOREG( fopen( filename, "r" ) == NULL );