|
|
Title |
Simple File I/O routines.
|
Summary |
File I/O is quite easy. Here are a few examples to ensure nothing is overlooked. |
Contributor |
John McTainsh
|
Published |
9-Sep-2000 |
Last updated |
9-Sep-2000 |
|
|
Description.
Accessing data in files is a key part of software development. Here are
some simple samples of file I/O that include error trapping.
Read a file into a CString.
bool LoadFile( CString sFileName, CString *psLoad )
{
TRACE( _T("LoadFile(%s,0x%p)\n"), sFileName, psLoad );
ASSERT( psLoad );
TRY
{
CFile fileIn( sFileName, CFile::modeRead );
int nLen = fileIn.GetLength();
if( nLen > 0 )
{
fileIn.Read( psLoad->GetBuffer( nLen ), nLen );
psLoad->ReleaseBuffer();
}
fileIn.Close();
}
CATCH(CFileException, pEx)
{
//Show error message
CString sErrorMess;
TCHAR szCause[255];
pEx->GetErrorMessage(szCause, 255);
sErrorMess.Format( _T("Error %s\n Reading %s"),
szCause,
pEx->m_strFileName );
AfxMessageBox( sErrorMess );
return false;
}
AND_CATCH(CMemoryException, pEx)
{
//Memory execption are often associated with
//CString objects. Normally, an application should
// do everything it possibly can to
// clean up properly and _not_ call AfxAbort().
AfxAbort();
return false;
}
END_CATCH;
return true;
}
Save a CString to a file.
bool SaveFile( CString sFileName, CString sSave )
{
TRACE( _T("SaveFile(%s,sSave)\n"), sFileName );
TRY
{
CFile fileOut( sFileName,
CFile::modeCreate | CFile::modeWrite );
int nLen = sSave.GetLength();
if( nLen > 0 )
{
fileOut.Write( sSave.GetBuffer( nLen ), nLen );
sSave.ReleaseBuffer();
}
fileOut.Close();
}
CATCH(CFileException, pEx)
{
//Show error message
CString sErrorMess;
TCHAR szCause[255];
pEx->GetErrorMessage(szCause, 255);
sErrorMess.Format( _T("Error %s\n Writing %s"),
szCause,
pEx->m_strFileName );
AfxMessageBox( sErrorMess );
return false;
}
AND_CATCH(CMemoryException, pEx)
{
//Memory execption are often associated with
//CString objects. Normally, an application should
// do everything it possibly can to
// clean up properly and _not_ call AfxAbort().
AfxAbort();
return false;
}
END_CATCH;
return true;
}
|