C programming tmpnam stdio.h

In C programming the <stdio.h> tmpname generates a string which is not the same as any existing file name.The declaration of the file is given below.

char *tmpnam(char *s);

s -A pointer to the string that stores the file name.

Return type
char* -A pointer to the file name.

Some points to note:

i) The ‘tmpnam’ is capable of generating TMP_MAX different string and whose value is at least 25.

ii)The function generates a different string each time it is called.

iii)If the functions cannot generate as name then NULL is returned.

iv)The argument passed to the function must be an array of ‘char’ type having size at least as large as ‘L_tmpnam’.

Code example

char str[L_tmpnam]=”” , *name=str ;

name=tmpnam( str );

printf( “Temporary name generated is ::%s” , name );

Ouput in Visual Studio,

C:\Users\..\AppData\Local\Temp\s2ck.0     (the part ‘..’ is your computer name)

Note here the name ‘s2ck.0’ is the temporary file name,the remaining values-“C:\Users\BAO\AppData\Local\Temp\”,is the directory where the temporary file is created.To confirm that a file with the name “s2ck.0” exists go to the directory “C:\Users\..\AppData\Local\Temp\” you will find your file there.

iv)If the argument passed to the function is a pointer to NULL then the function stores the file name generated in internal static object and returns a pointer to that object.Note subsequent calls to ‘tmpnam’ will modify the internal object.

Code example

char *str=NULL ;

str=tmpnam( str );

printf( “Temporary name generated is ::%s” , name );

Ouput in Visual Studio,


Only the name “s6zw.1” is the file name.Unfortunately in this case you won’t find the any file with the name “s6zw.1” in the directory “C:\Users\..\AppData\Local\Temp\”.

v)If we use the name obtained from ‘tmpnam’ to create a file,that does not mean the file behavior is same as the temporary file obtained by calling ‘tmpfile’ function.Unlike the temporary file created by ‘tmpfile’ which is removed automatically,the file created with the supplied temporary name will not be removed.It is the programmer responsibility to delete the file.

Link : C tmpfile stdio.h

A more exhaustive code example is given below.In this program we will create a file with the name obtain by ‘tmpnam’ and write content to it and also print out the content again.

Code example

#include <stdio.h>
#include <stdlib.h>

int main( )
char *str[L_tmpnam]=NULL ;

str=tmpnam( str );

printf( “File name::%s\n” , str );

FILE *fp = fopen(name , “w+”);

if (fp != NULL)
  fputs(“New string”, ffp); //writting string to the temporary file
  printf(“\nFile opening failed\n”);


int i = 0;

while ( (i = getc(fp)) != EOF)

fclose( fp );

return 0;

Output in Visual Studio,

The file name generated is ::C:\Users\BAO\AppData\Local\Temp\s448.0
New string

Related links

->C tmpfile stdio.h

->C fputs stdio.h

->C rewind stdio.h

->C rename stdio.h

->C remove stdio.h