Let us see mkstemp system call example program to make temporary file. mkstemp() system call is used to create a temporary file under Linux/Unix operating system.

         The mkstemp() function generates a unique temporary filename from
	 template, creates and opens the file, and returns an open file
	 descriptor for the file.

	 The last six characters of template must be "XXXXXX" and these are
	 replaced with a string that makes the filename unique.  Since it will
	 be modified, template must not be a string constant, but should be
	 declared as a character array.

	 The file is created with permissions 0600, that is, read plus write
	 for owner only.  The returned file descriptor provides both read and
	 write access to the file.  The file is opened with the open(2) O_EXCL
	 flag, guaranteeing that the caller is the process that creates the
	 file.

Let see below sample c code:

#include <stdlib.h>
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>

int main() 
{
	/* create a temp file in /tmp */
	int fd;
	char name[] = "/tmp/FooXXXXXX";
	fd = mkstemp(name);
	printf("Temp file name is %s \n", name);

	

	write(fd, "hello", 5);
	write(fd, " world", 7);

	/* close fd */
	close(fd);
}

The program will create a temporary file inside /tmp named as FooXXXXXX. The XXXXXX will be replaced with some random string. With the write() system call we are writing hello and world to the newly created temp file FooXXXXXX.

Let us see the contents of the file:

mkstemp system call example program

Ref:

http://man7.org/linux/man-pages/man3/mkstemp.3.html



Related Contents to follow