O template hierarchy Read and write sequential text files Random access files

Lecture 9 • File Processing – Streams – Stream I/O template hierarchy – Read and write sequential text files – Random access files • Binary files – R...
Author: Shanon Bailey
15 downloads 1 Views 133KB Size
Lecture 9 • File Processing – Streams – Stream I/O template hierarchy – Read and write sequential text files – Random access files • Binary files

– Reading and writing binary files

TNCG18(C++): Lec 9

1

Introduction • Storage of data – Arrays variables are temporary – Files are permanent • Magnetic disk, optical disk, tapes

• C++ views file as sequence of bytes – Ends with end-of-file marker 0

1

2

3

4

5

6

7

8

9

...

n-1

...

end-of-file marker

• C++ imposes no structure on file – Concept of "record" must be implemented by programmer TNCG18(C++): Lec 9

2

Files and Streams • When file opened – A stream object associated with it fstream file( "filename", fileOpenMode );

– cin, cout, etc. created when included • Communication between program and file/device badbit failbit …

file

Write file position pointer Read file position pointer 0

1

2

3

4

5

6

7

8

9

... ...

TNCG18(C++): Lec 9

n-1 end-of-file marker

3

Files and Streams • To perform file processing – #include and – Class templates • basic_ifstream (input) • basic_ofstream (output) • basic_fstream (I/O)

– typedefs for specializations that allow char I/O for files • ifstream (char input) • ofstream (char output) • fstream (char I/O)

TNCG18(C++): Lec 9

4

I/O Template Hierarchy • typedefs for specializations that allow char I/O • istream specialization of basic_istream (char input) • ostream specialization of basic_ostream (char output) • cin is an instance of istream • cout is an instance of ostream basic_ios

basic_istream

basic_ifstream

basic_ostream

basic_iostream

basic_ofstream

basic_fstream

TNCG18(C++): Lec 9

5

An Example // display single record void outputLine( ostream &output, const ClientData &record ) { output > score ) { moviesData