chapter 6: file i/o and serialize cfile class. 2 introduction (1/2) how to read/write a file...

38
Chapter 6: FILE I/O and Serialize CFile class

Upload: monica-richardson

Post on 17-Jan-2016

222 views

Category:

Documents


1 download

TRANSCRIPT

Chapter 6:FILE I/O and Serialize

CFile class

2

Introduction (1/2)

• How to read/write a file – Usual way of File I/O

• Use CFile class• Use member functions: CFile::Read() and CFile::Write() • Universal use. • Low level file I/O

– Serialize• Use CArchive class• Use operators: << and >> • Easy to use• Limited functionality

3

Introduction (2/2)

• MFC Class Hierarchy

Basic File I/O Derived Classes for specific purposes

4

CFile class

• Basic functionality

Open or create a file(Open). Read data at the file pointer(Read). Write data at the file pointer(Write). Change the file pointer (Seek). Close the file(Close).

CFile: Two ways to Open a file

1. Use CFile::Open member function

2. Use a constructor

CFile file ( filename, mode );CFile file ( filename, mode );

CFile file;file.Open( filename, mode, error );CFile file;file.Open( filename, mode, error );

6

CFile class (1/6)

• Open and Create: Use CFile::Open(..)

CFile file;

if( file.Open("mytest.txt", CFile::modeRead) == false)AfxMessageBox(_T(“Error”));

CFile file;file.Open( filename, mode, error );CFile file;file.Open( filename, mode, error );

7

CFile class (1/6)

• Open and Create: Use CFile::Open(..)• Get errors and related information

CFile file;CFileException e;

if(!file.Open("mytest.txt", CFile::modeReadWrite, &e)) e.ReportError();

CFile file;file.Open( filename, mode, error );CFile file;file.Open( filename, mode, error );

CFile class (1/6)

• Open and Create : Use the constructor

try { CFile file("mytest.txt", CFile::modeReadWrite); }catch (CFileException* e){ e->ReportError(); e->Delete();}

CFile file ( filename, mode );CFile file ( filename, mode );

9

CFile class (2/6)

• Access modes of CFileflags meaning

CFile::modeCreate Directs the constructor to create a new file. If the file exists already, it is truncated to 0 length

CFile::modeNoTruncate

Combine this value with modeCreate. If the file being created already exists, it is not truncated to 0 length.

CFile::modeRead Requests read access only

CFile::modeReadWrite Requests read and write access

CFile::modeWrite Requests write access only

CFile::shareDenyNone Opens the file nonexclusively

CFile::shareDenyRead Denies read access to other parties.

CFile::shareDenyWrite

Denies write access to other parties.

CFile::shareDenyExclusive

Denies both read and write access to other parties (default).

10

CFile class(3/6)

• Close a file: Destructor closes it automatically

void CExFileView::OnLButtonDblClk(UINT nFlags, CPoint point){ CFile file; CFileException e; if(!file.Open("mytest.txt", CFile::modeReadWrite|

CFile::modeCreate, &e)) { e.ReportError(); return; } // skip ...} // -> CFile::~CFile() is called and close the file automatically.

11

CFile class (4/6)

• Close a file: CFile::Close member function– When opening a multiple files

void CExFileView::OnLButtonDblClk(UINT nFlags, CPoint point)

{ CFile file; CFileException e; if(!file.Open("mytest.txt“, CFile::modeReadWrite|

CFile::modeCreate| CFile::modeNoTruncate, &e))

{ e.ReportError(); return; }

file.Close();}

12

CFile class (5/6)

• Read and Write

• Change the file pointer

UINT CFile::Read (void* lpBuf, UINT nCount) ;void CFile::Write (const void* lpBuf, UINT nCount) ;

ULONGLONG CFile::Seek (LONGLONG lOff, UINT nFrom) ;

nFrom meaning

CFile::begin Move the file pointer by lOff bytes from the beginning

CFile::current

Move the file pointer by lOff bytes from the current position

CFile::end Move the file pointer by lOff bytes from the end

13

CFile class: Write Data

CFile file(_T(“test.txt“), CFile::modeCreate|CFile::modeWrite);

int a = 30;int b = 20;

file.Write(&a, sizeof(a));file.Write(&b, sizeof(b));

void CFile::Write (const void* lpBuf, UINT nCount) ;

14

CFile class: Read Data

CFile file;CFileException e;

if(!file.Open(_T("test.txt“), CFile::modeRead, &e)){

e.ReportError();return;

};

int a,b;file.Read(&a, sizeof(a));file.Read(&b, sizeof(b));

UINT CFile::Read (void* lpBuf, UINT nCount) ;

15

CFile class: Read Data

CFile file;CFileException e;if(!file.Open(_T("test.txt“), CFile::modeRead, &e)){

e.ReportError();return;

};int a,b;file.Read(&a, sizeof(a));file.Read(&b, sizeof(b));

CString str;str.Format(_T("a=%d b=%d"), a, b);AfxMessageBox(str);

UINT CFile::Read (void* lpBuf, UINT nCount) ;

Coding Practice

1. Create variables “a” and “b”2. When clicking mouse left button, create “test.txt”

file, and store the values of “a” and “b” variables3. When clicking mouse right button, read “test.txt”

file, and read the values of “a” and “b” variables4. Show the data by using AfxMessageBox function

17

CFile class (6/6)

• Miscellaneous functions– CFile::GetLength(), CFile::SetLength()

• Get or change the file size.

– CFile::GetPosition()• Get the file position.

– CFile::LockRange(), CFile::UnlockRange()• Lock or Unlock the file. If lock a file, other process can

not access the file.

– CFile::GetFilePath(), CFile::GetFileName()• Get full path or file name as a CString

18

CStdioFile Class (1/2)

• For read/write a text file– CStdioFile::ReadString : to read a text from a file

– CStdioFile::WriteString : to write a text to a file

CString str;file.ReadString(str);CString str;file.ReadString(str);

CString str =_T(“Output”);file.WriteString(str);CString str =_T(“Output”);file.WriteString(str);

19

CStdioFile Class (2/2)

• Coding example: Make lower characters into upper characters and save it.

CStdioFile file1; file1.Open(_T("test1.txt"), CFile::modeRead);

CStdioFile file2; file2.Open(_T("test2.txt"),CFile::modeWrite|

CFile::modeCreate);

CString str; while(file1.ReadString(str))

{ str.MakeUpper(); file2.WriteString(str + _T("\n")); }

20

Utility class: CFileFind Class

• To search a file in the local disk.– CFileFile::FindFile() function to search

CFileFind finder;bool bExist = finder.FindFile(“MyText.txt”);CFileFind finder;bool bExist = finder.FindFile(“MyText.txt”);

21

CFileFind Class (2/2)

• Coding Example: show every files in the current directory

CFileFind finder; BOOL bWorking = finder.FindFile(_T("*.*"));

while(bWorking){

bWorking = finder.FindNextFile(); if(finder.IsDirectory()) TRACE("[%s]\n", (LPCTSTR)finder.GetFileName()); else TRACE("%s\n", (LPCTSTR)finder.GetFileName()); }

Asterisk: Wildcard symbol

FILE I/O

Serialization and the CArchive Class

23

Serialization basics (1/8)

– serialization is … (from Wikipedia)• the process of saving an object onto a storage medium

(such as a file, or a memory buffer) to transmit it across a network connection link in binary form.

• The series of bytes or the format can be used to re-create an object that is identical in its internal state to the original object (actually, a clone).”

24

Serialization basics (2/8)

• Read data by using CFile

CFile file;CFileException e;if(!file.Open("mytest.dat",

CFile::modeReadWrite|CFile::modeCreate, &e)){ e.ReportError(); return}

int a = 100;int b = 200;file.Write(&a, sizeof(a));file.Write(&b, sizeof(b));

25

Serialization basics (3/8)

• Read data by serialization

CFile file;CFileException e;if(!file.Open("mytest.dat", CFile::modeReadWrite|

CFile::modeCreate, &e)){ e.ReportError(); return;}

int a = 100;int b = 200;CArchive ar (&file, CArchive::store);ar << a << b;

26

Serialization basics (4/8)

• Write data by using CFile

CFile file;CFileException e;if(!file.Open("mytest.dat", CFile::modeRead, &e)){ e.ReportError(); return;}

int a, b;file.Read(&a, sizeof(a));file.Read(&b, sizeof(b));TRACE("a = %d, b = %d\n", a, b);

27

Serialization basics (5/8)

• Write data by serialization

CFile file;CFileException e;if(!file.Open("mytest.dat", CFile::modeRead, &e)){ e.ReportError(); return;}

int a, b;CArchive ar (&file, CArchive::load);ar >> a >> b;TRACE("a = %d, b = %d\n", a, b);

28

Serialization (6/8)

• CArchive Class constructor:

– pFile• Pointer to CFile object

– nMode• CArchive::load or CArchive::store

– nBufSize• Buffer size (don’t need to change it)

– lpBuf• Buffer address (don’t need to change it)

CArchive::CArchive (CFile* pFile, UINT nMode, int nBufSize = 4096, void* lpBuf = NULL) ;

29

Serialization basics (7/8)

• Data types ready to the serialization

Data types

Basic data types

BYTE, WORD, LONG, DWORD, float, double, int, short, char, wchar_t, unsigned, bool, ULONGLONG, LONGLONG

MFC data types

RECT, POINT, SIZE, CRect, CPoint, CSize, CString, CTime, CTimeSpan, COleVariant, COleCurrency, COleDateTime, COleDataTimeSpan

30

Serialization basics (8/8)

• Concept of serialization

CArchive ar(...);ar << a << b;

CArchive ar(...);ar >> a >> b;

CArchive Object CFile ObjectLocal disk

a, b

Coding practice

• Make a program for typing

• Mouse left click: Save the contents as “testString.dat” file

• Mouse right click: Load the contents from “testString.dat” file and show it.

32

Serialization Implementation (1/5)

• How to make your own class to support the serialization?

class CMyData{public: CString m_str; COLORREF m_color;public: CMyData(CString &str, COLORREF &color) { m_str = str; m_color = color; } virtual ~CMyData();};

33

Serialization Implementation (2/5)

• It will not support any serialization by default

void CYourProgram::SaveOrLoad(CArchive& ar){ if (ar.IsStoring()) { ar << m_data; } else { ar >> m_data; }}

X

34

Serialization Implementation (3/5)

• Change your class to support the serialization// in your header fileclass CMyData : public CObject ①{ DECLARE_SERIAL(CMyData) ②public: CString m_str; COLORREF m_color;public: CMyData() { } ③ CMyData(CString &str, COLORREF &color) { m_str = str; m_color = color; } virtual ~CMyData(); void Serialize(CArchive& ar); ④};

35

Serialization Implementation (4/5)

• Change your class to support the serialization (cont'd)// In your cpp fileCMyData::~CMyData(){}

IMPLEMENT_SERIAL(CMyData, CObject, 1) ⑤

void CMyData::Serialize (CArchive& ar) ⑥{ CObject::Serialize(ar); if(ar.IsStoring()) ar << m_str << m_color; else ar >> m_str >> m_color;}

36

Serialization Implementation (5/5)

• Now your own class support serialization

void CYourProgram ::SaveOrLoad(CArchive& ar){ if (ar.IsStoring()) { m_data.Serialize(ar); } else { m_data.Serialize(ar); }}

O

Downside of the Serialize

• The whole file should be read• The whole file should be written• Extra information should be stored.

Coding Practices

• Draw many circles by using mouse left clicks.

• Add menu ‘Save’ and save the information of the circles as “circle.dat” file

• Add menu ‘Load’ and load the data from the file “circle.dat”.