All most all of the programing languages allow us to create temporary files and directories. In this post I am going to explore the creation of temporary files in C, Perl and Shell script.
C Implentation:
To create temporary files in C, we make use of the library function
mkstemp () which is defined under
stdlib header file. The syntax of
mkstemp ()
int mkstemp (char *template);
The mkstemp file takes a character array (make sure that its not a character constant but an array, as it will be modified) and returns a file descriptor to the file. It will create a file with the default permissions.
Here, the template is a character array which has its last 6 characters marked
"XXXXXX". These characters will be used to generate a unique name.
An example of template can be
"fileXXXXXX";
Note:
mkstemp() will create the temporary file in the current directory. To create a file in a particular directory prefix the absolute path of the directory like to create a file under /tmp use
"/tmp/fileXXXXXX"
A sample C program
#include <stdio.h>
#include <stdlib.h>
int
main ()
{
char filename[] = "/tmp/fileXXXXXX";
int fd;
fd = mkstemp (filename);
printf ("file=%s\n", filename);
/* perform the operation on the file desc
* ....
*/
close (fd);
unlink (filename);
return 0;
}
The temporary file is not deleted hence it must be deleted manually.
You may also look into
"mkdtemp (3)", "mkostemp (3)"
Shell implementation:
The create a temporary file in shell scripts, make use of $tempfile. It creates a temporary file in
/tmp directory by default.
Sample program:
#!/bin/sh
x=$(tempfile)
## Perform operations on file
rm $x
Perl implementation:
Perl makes use of the
File module to create the temporary files. I think perl gives more liberty to us. We can tune it according to our need like one of the main things that other languages missed is the deletion of the temporary file when the process terminates and many more. Like
Shell perl also creates the temporary file under
/tmp directory.
Sample program:
#!/usr/bin/perl
use File::Temp 'tempfile';
($handle, $filename) = tempfile (UNLINK => 1, SUFFIX => '.dsk');
## perform the operation on the file
The tempfile function returns a handle and the filename.