Click here to Skip to main content
15,885,278 members
Articles / Desktop Programming / Win32
Tip/Trick

Generate temporary files with any extension

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
12 Jan 2012CPOL 27.9K   3   3
How to get temporary files with any extension.

There isn't any Win32 API to generate temporary files with any extension, so I wrote my own function:


C++
BOOL GetTemporaryFilePath(CString strExtension, CString& strFileName)
{
     TCHAR lpszTempPath[MAX_PATH] = { 0 };
     if (!GetTempPath(MAX_PATH, lpszTempPath))
         return FALSE;

     TCHAR lpszFilePath[MAX_PATH] = { 0 };
     do {
         if (!GetTempFileName(lpszTempPath, NULL, 0, lpszFilePath))
             return FALSE;

         strFileName = lpszFilePath;
         VERIFY(::DeleteFile(strFileName));
         strFileName.Replace(_T(".tmp"), strExtension);
     }
     while (_taccess(strFileName, 00) != -1);

     OutputDebugString(_T("GetTemporaryFilePath = '") + strFileName + _T("'\n"));
     return TRUE;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer NXP Semiconductors
Romania Romania
My professional background includes knowledge of analyst programmer for Microsoft Visual C++, Microsoft Visual C#, Microsoft Visual Basic, Sun Java, assembly for Intel 80x86 microprocessors, assembly for PIC microcontrollers (produced by Microchip Inc.), relational databases (MySQL, Oracle, SQL Server), concurrent version systems, bug tracking systems, web design (HTML5, CSS3, XML, PHP/MySQL, JavaScript).

Comments and Discussions

 
Suggestiona note to print out the temp file name Pin
Southmountain12-Jul-21 13:50
Southmountain12-Jul-21 13:50 
Questionupvote for strFileName.Replace(_T(".tmp"), strExtension); Pin
milesma8014-Sep-15 15:21
milesma8014-Sep-15 15:21 
GeneralAre you use MFC class CString here? Pin
Igor Galchuk2-Feb-12 7:47
Igor Galchuk2-Feb-12 7:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.