|
-
February 18th, 2007, 07:59 AM
#11
Re: CFile
Here is the example
Code:
#include "stdafx.h"
#include "ConsMFC.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
CWinApp theApp;
int _tmain()
{
// initialize MFC and print and error on failure (added by AppWizard).
if(!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
return 1;
}
LPCTSTR pszFilter = _T("Text files (*.txt)|*.txt|All files(*.*)|*.*||");
TRY
{
CFileDialog dlgOpen(TRUE, NULL, NULL, OFN_HIDEREADONLY, pszFilter);
if(IDOK == dlgOpen.DoModal())
{
CStringArray arrLines;
CString strFileRead = dlgOpen.GetPathName();
// open the file to be read
CStdioFile fileRead(strFileRead, CFile::modeRead);
CString strLine;
while(fileRead.ReadString(strLine))
{
// filters (just as an example)
// only lines which begins with 'A' or 'a'
if(!strLine.IsEmpty()
&& !strLine.Left(1).CompareNoCase(_T("a")))
{
arrLines.Add(strLine);
}
}
fileRead.Close();
CFileDialog dlgSave(FALSE, _T("txt"), strFileRead,
OFN_OVERWRITEPROMPT, pszFilter);
if(IDOK == dlgSave.DoModal())
{
CString strFileWrite = dlgSave.GetPathName();
// open the file for write
CStdioFile fileSave(strFileWrite,
CFile::modeWrite|CFile::modeCreate);
const int nSize = arrLines.GetSize();
for(int nIndex = 0; nIndex < nSize; nIndex++)
{
// add CR-LF then write the line
strLine.Format(_T("%s\r\n"), arrLines.GetAt(nIndex));
fileSave.WriteString(strLine);
}
}
}
}
CATCH_ALL(e)
{
e->ReportError(); // shows if something goes wrong
}
END_CATCH_ALL
return 0;
}
NOTES:
- I have used CStdioFile instead of CFile to easier read/write line-by line from/into the text file. As long as CStdioFile is derived from CFile that does not conflict with your initial requirements.
- I have used CFileDialog to select files to read and write just for an example. You can modify the code according to your needs, as for example getting the file names from command line arguments.
- I have used TRY/CATCH MFC macros to handle the exceptions which can be thrown from CFile (CStdioFile) methods.
- You can still replace my ugly
MFC code with plain WinAPI (like somebody suggested above), but first be sure you have enough "Antinevralgic" pills available... 
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|