Home

Microsoft Visual C++/MFC File Processing: MFC's Standard I/O File Processing

       

Introduction

 

The MFC library provides it own version of C's file processing. This is done through a class named CStdioFile. The CStdioFile class is derived from CFile.

As done for the FILE structure, to start normal file input/output operations, declare a variable of type CStdioFile. This class has five constructors whose syntaxes are:

CStdioFile();
CStdioFile(CAtlTransactionManager* pTM);
CStdioFile(FILE* pOpenStream);
CStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags);
CStdioFile(LPCTSTR lpszFileName, UINT nOpenFlags, CAtlTransactionManager* pTM);

The default constructor allows you to initiate file processing without giving much detail. If you use it, you can then call the Open() method that the CStdioFile class inherits from CFile. Pass the same arguments you would for a CFile variable.

Practical LearningPractical Learning: Introducing MFC's Standard File Processing

  1. To create a new application, on the main menu, click File -> New Project...
  2. In the middle list, click MFC Application
  3. Set the Name to LoanPreparation1
  4. Click OK
  5. In the first page of the MFC Application Wizard, click Next
  6. In the second page of the wizard, click Dialog Box
  7. Click Next
  8. In the third page of the wizard, change the Dialog Title to Loan Preparation
  9. Click Next twice
  10. Click Finish
  11. On the dialog box, click TODO: and press Delete
  12. Press the OK button and press Delete
  13. Click the Cancel button to select it
  14. In the Properties window, click Caption, type Close and press Enter
  15. Design the dialog box as follows:
     
    Loan Evaluation
    Control Caption ID Right Align Text
    Static Text Static Text Prepared By:    
    Edit Control Edit Control   IDC_CUSTOMERNAME  
    Static Text Static Text Prepared For:    
    Edit Control Edit Control   IDC_EMPLOYEENAME  
    Static Text Static Text ________________    
    Static Text Static Text Loan Amount:    
    Edit Control Edit Control   IDC_PRINCIPAL True
    Static Text Static Text Interest Rate:    
    Edit Control Edit Control   IDC_INTERESTRATE True
    Static Text Static Text %    
    Static Text Static Text Paid In:    
    Edit Control Edit Control   IDC_PERIODS True
    Static Text Static Text Months    
    Button Button Evaluate IDC_EVALUATE  
    Static Text Static Text _________________    
    Static Text Static Text Future Value:    
    Edit Control Edit Control   IDC_FUTUREVALUE True
    Static Text Static Text Monthly Payment:    
    Edit Control Edit Control   IDC_MONTHLYPAYMENT True
    Static Text Static Text _________________    
    Static Text Static Text Save As:    
    Edit Control Edit Control   IDC_FILESAVE True
    Button Button Save IDC_SAVE_BTN  
    Static Text Static Text File to Open:    
    Edit Control Edit Control   IDC_FILEOPEN True
    Button Button Open IDC_OPEN_BTN  
    Static Text Static Text File Name:    
    Button Button Reset IDC_RESET_BTN  
    Button Button Close IDCANCEL  
  16. Right-click each edit control, click Add Variable, select the category as Value, set the options as follows and click Finish on each:
     
    Control ID Category Variable Type Variable Name
    IDC_CUSTOMERNAME Value CString m_CustomerName
    IDC_EMPLOYEENAME Value CString m_EmployeeName
    IDC_PRINCIPAL Value CString m_Principal
    IDC_INTERESTRATE Value CString m_InterestRate
    IDC_PERIODS Value CString m_Periods
    IDC_FUTUREVALUE Value CString m_FutureValue
    IDC_MONTHLYPAYMENT Value CString m_MonthlyPayment
    IDC_FILESAVE Value CString m_FileSave
    IDC_FILEOPEN Value CString m_FileOpen
  17. Access the source file of the dialog box and change the initializations in the constructor as follows:
    CLoanPreparation1Dlg::CLoanPreparation1Dlg(CWnd* pParent /*=NULL*/)
    	: CDialogEx(CLoanPreparation1Dlg::IDD, pParent)
    	, m_CustomerName(_T(""))
    	, m_EmployeeName(_T(""))
    	, m_Principal(_T("0.00"))
    	, m_InterestRate(_T("0.00"))
    	, m_Periods(_T("0"))
    	, m_FutureValue(_T("0.00"))
    	, m_MonthlyPayment(_T("0.00"))
    	, m_FileSave(_T(""))
    	, m_FileOpen(_T(""))
    {
    	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
    }
  18. Return to the dialog box
  19. Double-click the Evaluate button
  20. Implement the event as follows:
    void CLoanPreparation1Dlg::OnBnClickedEvaluate()
    {
    	UpdateData(TRUE);
    
    	double Principal      = _wtof(m_Principal);
    	double InterestRate   = _wtof(m_InterestRate) / 100;
    	double Periods	      = _wtof(m_Periods) / 12;
    	double InterestAmount = Principal * InterestRate * Periods;
    	double FutureValue    = Principal + InterestAmount;
    	double MonthlyPayment = FutureValue / _wtof(m_Periods);
    	
    	m_FutureValue.Format(L"%.2f", FutureValue);
    	m_MonthlyPayment.Format(L"%.2f", MonthlyPayment);
    
    	UpdateData(FALSE);
    }
  21. Return to the dialog box
  22. Double-click the Reset button
  23. Implement the event as follows:
    void CLoanPreparation1Dlg::OnBnClickedResetBtn()
    {
    	m_CustomerName 	 = L"";
    	m_EmployeeName 	 = L"";
    	m_Principal    	 = L"0.00";
    	m_InterestRate 	 = L"0.00";
    	m_Periods      	 = L"0.00";
    	m_FutureValue  	 = L"0.00";
    	m_MonthlyPayment = L"0.00";
    	m_FileSave 	 = L"";
    	m_FileOpen 	 = L"";
    
    	UpdateData(FALSE);
    }

Writing to Standard Stream

Naturally the primary operation you would want to perform on a file consists of writing one or more values to it. To let you continually write a string without any concern for the end of line, you can use the Write() method that the CStdioFile gets from its parent. If you want the compiler to add a new line at the end of each written string, you can use the WriteString() method of the CStdioFile class. Its syntax is:

virtual void WriteString(LPCTSTR lpsz);
 
 
 

Practical LearningPractical Learning: Writing Values to a Stream

  1. On the dialog box, double-click the Save button
  2. Implement its event as follows:
    void CLoanPreparation1Dlg::OnBnClickedSaveBtn()
    {
    	CStdioFile sioLoan;
    	UpdateData(TRUE);
    	
    	if( m_EmployeeName.GetLength() == 0 )
    	{
    		AfxMessageBox(L"You must specify the name of the employee who prepared this loan.");
    		return;
    	}
    	
    	if( m_CustomerName.GetLength() == 0 )
    	{
    		AfxMessageBox(L"You must specify the name of the customer for whom the loan was prepared.");
    		return;
    	}
    	
    	if( m_FileSave.GetLength() == 0 )
    	{
    		AfxMessageBox(L"You must enter a name for the file to save.");
    		return;
    	}
    
    	sioLoan.Open(m_FileSave + L".txt", CFile::modeCreate | CFile::modeWrite | CFile::typeText);
    
    	sioLoan.WriteString(m_EmployeeName);
    	sioLoan.WriteString(L"\n");
    	sioLoan.WriteString(m_CustomerName);
    	sioLoan.WriteString(L"\n");
    	sioLoan.WriteString(m_Principal);
    	sioLoan.WriteString(L"\n");
    	sioLoan.WriteString(m_InterestRate);
    	sioLoan.WriteString(L"\n");
    	sioLoan.WriteString(m_Periods);
    	sioLoan.WriteString(L"\n");
    	sioLoan.WriteString(m_FutureValue);
    	sioLoan.WriteString(L"\n");
    	sioLoan.WriteString(m_MonthlyPayment);
    
    	sioLoan.Close();
    
    	OnBnClickedResetBtn();
    	UpdateData(FALSE);
    }
  3. Execute the application to test
  4. Enter the Prepared By value as Ernestine Stanley
  5. Enter the Prepared For name as Benjamin Greens
  6. Enter the Loan Amount as 5000.00
  7. Enter the Interest Rate as 12.25
  8. Enter the Paid In value as 36
     
    Loan Evaluation
  9. Click Evaluate
  10. In the Save As edit control, type BG as the name of the file
     
    Loan Evaluation
  11. Click Save
  12. Close the dialog box and return to your programming environment

Reading From a Standard Stream

To read a continuous string from a stream, you can call the Read() method that the CStdioFile class gets from its parent. If you have a document made of various paragraphs separated by new lines, to let you read each line, the CStdioFile class is equipped with the ReadString() method. It comes in two versions whose syntaxes are:

virtual LPTSTR ReadString(LPTSTR lpsz, UINT nMax);
virtual BOOL ReadString(CString& rString);

The first version is used to write a C string to the file and you must specify the number of characters you are writing, as the second argument. The second version can be more convenient as it accepts a CString value.

Practical LearningPractical Learning: Reading Values From a Stream

  1. On the dialog box, double-click the Open button
  2. Implement its event as follows:
    void CLoanPreparation1Dlg::OnBnClickedOpenBtn()
    {
    	UpdateData(TRUE);
    	
    	if( m_FileOpen.GetLength() == 0 )
    	{
    		AfxMessageBox(L"You must enter a name for the file to open.");
    		return;
    	}
    
    	CStdioFile sioLoan;
    	sioLoan.Open(m_FileOpen + L".txt", CFile::modeRead | CFile::typeText);
    
    	sioLoan.ReadString(m_EmployeeName);
    	sioLoan.ReadString(m_CustomerName);
    	sioLoan.ReadString(m_Principal);
    	sioLoan.ReadString(m_InterestRate);
    	sioLoan.ReadString(m_Periods);
    	sioLoan.ReadString(m_FutureValue);
    	sioLoan.ReadString(m_MonthlyPayment);
    
    	UpdateData(FALSE);
    	sioLoan.Close();
    }
  3. Execute the application to test the dialog box
  4. In the File to Open edit control, enter the name of the file you previously created (BG) and click Open
  5. Close the dialog box and return to your programming environment
 
 
   
 

Home Copyright © 2010-2016, FunctionX