_tempnam() always returns a filename in the "c:\\temp" directory, regardless of the parameters. This example was extracted from MSDN. I need to generate a unique filename in a directory other than c:\temp -- any ideas how to do that other than writing my own function? maybe a c++ solution?

Note this is one of may examples where Microsoft uses void main() instead of int main() :evil: Not that I mind -- but can be confusing to newbes.

Thanks

#include <stdio.h>

void main( void )
{
   char  *name2;


   /* Create a temporary filename in temporary directory with the
    * prefix "stq". The actual destination directory may vary
    * depending on the state of the TMP environment variable and
    * the global variable P_tmpdir.
    */
   
   if( ( name2 = _tempnam( "c:\\h", "stq" ) ) != NULL )
   {
      printf( "%s is safe to use as a temporary file.\n", name2 );
	  FILE*fp = fopen(name2,"wt");
	  fprintf(fp,"Hello World\n");
	  fclose(fp);
   }
   else
      printf( "Cannot create a unique filename\n" );
}

Recommended Answers

All 4 Replies

>I need to generate a unique filename in a directory other than c:\temp
Is this a directory that you specify or just any directory other than C:\temp? If it's the latter then tmpnam will create the file in the local directory. If it's the former then you're SOL and need to do it manually.

Is this a directory that you specify.

A directory I specify, as shown in the example program I posted. This might be another famous example where MSDN is wrong.

I decided to create unique filenames another way by using the current system time from GetLocalTime().

Thanks anyway for your reply.

Ah! Ha! I overlooked that -- I have a temp and tmp environment variables.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.