Generate a temporary file path with a temp file name in Windows (C++/MFC)



Following function creates a temporary file path with a specific file extension. Optionally, it also creates the temporary file. Coded in C++/MFC (Windows).

 
CString	GenerateTempFilePath(BOOL bCreateDummyFile, CString strFileExtension)
{
 
	TCHAR szFilePath[MAX_PATH];
	CString strTempFolderPath = GetTempFolder();
	AppendBackslash(strTempFolderPath);
 
	if (strFileExtension.Find(_T('.')) == -1)
	{
		strFileExtension = _T(".") + strFileExtension;
	}
 
	//this will also create a file
	GetTempFileName(strTempFolderPath, NULL, 0,szFilePath);
	//delete the temporary file created
	DeleteFile(szFilePath);
 
	if (!strFileExtension.IsEmpty())
	{
		PathRemoveExtension(szFilePath);
		PathAddExtension(szFilePath, strFileExtension);
 
		if (bCreateDummyFile)
		{
			HANDLE hFile = CreateFile(szFilePath, 0, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
			if (hFile)
			{
				CloseHandle(hFile);
			}
		}
	}
 
	return szFilePath;
}


Leave a Reply

Your email address will not be published. Required fields are marked *