Search This Blog

Monday, May 25, 2009

Code to Create a file, If file exist already append a GUID with that file and write the content



#pragma comment (lib, "Rpcrt4.lib")

CString GetUniqueGUID( )
{
HRESULT hr = NULL;
CString sUUID(_T(""));
UUID *pUUID = NULL;
BOOL bAllocated = FALSE;
unsigned char *sTemp = NULL;

if (pUUID == NULL)
{
pUUID = new UUID;
bAllocated = TRUE;
}

if (pUUID != NULL)
{
hr = UuidCreate( pUUID );
if (hr == RPC_S_OK)
{
hr = UuidToString(pUUID, &sTemp);
if (hr == RPC_S_OK)
{
sUUID = sTemp;
sUUID.MakeUpper();
RpcStringFree(&sTemp);
}
}
if (bAllocated)
{
delete pUUID;
pUUID = NULL;
}
}
return sUUID;
}


void CreateFileWithoutReplacingExisting(CString & csFileName , CString & csContent )
{

CFileStatus cf;
if(CFile::GetStatus(csFileName,cf)) // File Exist
{
CString csExt ;
CString csGUID=GetUniqueGUID();
csGUID = "_"+csGUID;
int nPos = csFileName.ReverseFind('.');
if(nPos > -1 )
{
csExt = csFileName.Mid(nPos);
csFileName = csFileName.Left(nPos);
csFileName = csFileName+csGUID+"."+csExt;
}
}
CreateFile(csFileName,csContent);

}


int CreateFile(LPCTSTR lpcFileName, LPCTSTR lpcText)
{
if( !lpcFileName || lpcFileName[0]=='\0' )
{
return -1;
}
if(!lpcText || lpcText[0]=='\0') return -1;

CFile cf;
CFileException cfe;

try
{
if(!cf.Open(lpcFileName,CFile::modeCreate|CFile::modeWrite|CFile::shareDenyWrite, &cfe))
{
return 0;
}

cf.Write(lpcText, lstrlen(lpcText) );
cf.Close();
}
catch(CFileException *ce)
{
ce->Delete();
cf.Close();
return -1;
}
return 1;
}

No comments: