Search This Blog

Showing posts with label File. Show all posts
Showing posts with label File. Show all posts

Sunday, March 21, 2010

Check whether a file exist

//Check whether a file exist
//Portable to linux

#include <sys/stat.h>
#include <string>
using namespace std;

bool FileExists(string strFilename)
{
struct stat stFileInfo;
bool blnReturn= false;
int intStat=-1;
// Attempt to get the file attributes
intStat = stat(strFilename.c_str(),&stFileInfo);
if(intStat == 0)
{
// We were able to get the file attributes
blnReturn = true;
}
else
{
// We were not able to get the file attributes.
blnReturn = false;
}
return blnReturn;
}

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;
}