lecture 9 - linköping universitywebstaff.itn.liu.se/~aidvi/courses/07/c++/lectures/lec9.pdf6 7...
TRANSCRIPT
![Page 1: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/1.jpg)
TNCG18(C++): Lec 9 1
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
![Page 2: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/2.jpg)
TNCG18(C++): Lec 9 2
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
• C++ imposes no structure on file– Concept of "record" must be implemented by programmer
0 31 2 4 5 8 9
...
... n-1
end-of-file marker
6 7
![Page 3: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/3.jpg)
TNCG18(C++): Lec 9 3
Files and Streams
• When file opened– A stream object associated with itfstream file( "filename", fileOpenMode );
– cin, cout, etc. created when <iostream> included• Communication between program and file/device
0 31 2 4 5 8 9
...
... n-1
end-of-file marker
6 7
Write file position pointer
Read file position pointer
badbitfailbit
…
file
![Page 4: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/4.jpg)
TNCG18(C++): Lec 9 4
Files and Streams
• To perform file processing– #include <iostream> and <fstream>– 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)
![Page 5: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/5.jpg)
TNCG18(C++): Lec 9 5
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_fstream
basic_ios
basic_ifstream basic_ofstreambasic_iostream
basic_istream basic_ostream
![Page 6: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/6.jpg)
TNCG18(C++): Lec 9 6
An Example// display single recordvoid outputLine( ostream &output, const ClientData &record ){
output << left << setw( 10 ) << record.getAccountNumber()<< setw( 16 ) << record.getLastName()<< setw( 11 ) << record.getFirstName()<< setw( 10 ) << setprecision( 2 ) << right << fixed
<< showpoint << record.getBalance() << endl;
} // end function outputLine
ClientData client(1234, “Mark Junior”, -210);
ofstream ClientFile( "clients.dat", ios::out );
…
outputLine(cout, client);
outputLine(ClientFile, client);
ofstream is a derived class of ostream
![Page 7: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/7.jpg)
TNCG18(C++): Lec 9 7
Creating a Sequential-Access File• To open file
– Create a stream object• Creates "line of communication" from object to file
– Classes• ifstream (input only)• ofstream (output only)• fstream (I/O)
– Constructors take file name and file-open modeofstream outClientFile( "filename", fileOpenMode );
– To attach a file laterofstream outClientFile;outClientFile.open( "filename", fileOpenMode);
![Page 8: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/8.jpg)
TNCG18(C++): Lec 9 8
Creating a Sequential-Access File
• File-open modes
– ofstream opened for output by defaultofstream outClientFile( "clients.dat", ios::out );
ofstream outClientFile( "clients.dat");
fstream ClientFile( "clients.dat“, ios::out | ios::in);
Mode Description
ios::app Write all output to the end of the file.
ios::ate Open a file for output and move to the end of the file (normally used to append data to a file). Data can be written anywhere in the file.
ios::in Open a file for input.
ios::out Open a file for output.
ios::trunc Discard the file’s contents if it exists (this is also the default action for ios::out)
ios::binary Open a file for binary (i.e., non-text) input or output.
![Page 9: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/9.jpg)
TNCG18(C++): Lec 9 9
File Operations• Overloaded operator!()
– !outClientFile– Returns nonzero (true) if badbit or failbit set
• Opened non-existent file for reading, wrong permissions
• Overloaded operator void*()– Converts stream object to pointer– 0 when when failbit or badbit set, otherwise nonzero
• failbit set when EOF found
while ( cin >> myVariable );
• stream >> var; returns the stream object• Implicitly converts cin to pointer• Loops until EOF
![Page 10: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/10.jpg)
TNCG18(C++): Lec 9 10
File Operations
• Writing to file (just like cout)– outClientFile << myVariable
• Closing file– outClientFile.close()
– Automatically closed when destructor called
• Example: Creating a text file of movie scoresname1 score1name2 score2name3 score3…
![Page 11: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/11.jpg)
TNCG18(C++): Lec 9 11
Open a File
#include <iostream>#include <fstream>
//ofstream constructor opens file ofstream moviesData( “reviews.txt", ios::out );
//exit program if unable to create fileif ( !moviesData ) {
cerr << "File could not be opened" << endl;return;
}
Notice the the header files required for file I/O.
![Page 12: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/12.jpg)
TNCG18(C++): Lec 9 12
Write Data to a Text File
char name[40];int score;
//read films name and score from cin, //then write them into file
while ( cin >> name >> score ) {moviesData << name << ' ' << score << endl;
}
![Page 13: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/13.jpg)
TNCG18(C++): Lec 9 13
Reading Data from a Text File• Open the file
ifstream file( “fileName", ios::in );
• Test if the file was properly opened!file ! is overloaded
• Read the file until EOFwhile ( file >> myVariable ) { … }
– Stops when EOF found (gets value 0)– operator void*() converts a to pointer
• Testing if end-of-file reached– file.eof()
![Page 14: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/14.jpg)
TNCG18(C++): Lec 9 14
Open Movies Data File#include <iostream>#include <fstream>
//ofstream constructor opens fileifstream moviesFile( "reviews.txt", ios::in );
//exit program if unable to open fileif ( !moviesFile ) {
cerr << "File could not be opened" << endl;return;
}
![Page 15: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/15.jpg)
TNCG18(C++): Lec 9 15
Read Movies Data File
char name[40];int score;
//read films name and score from file while( moviesFile >> name >> score ) {
cout << name << ": " << grade << endl;}
Read from file until EOF found.
![Page 16: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/16.jpg)
TNCG18(C++): Lec 9 16
Read Movies Data File• Assume that the file looks as follows
Mystic River: 4Lost: 1The Reader: 5Pulp Fiction: 5No Country for Old Man: 5…
moviesFile.getline(name, 40, ':');moviesFile >> score;while ( !moviesFile.eof() ) {
cout << name << ": " << score << endl;moviesFile.ignore();moviesFile.getline(name, 40, ':');moviesFile >> score;
}
![Page 17: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/17.jpg)
TNCG18(C++): Lec 9 17
Read Movies Data File• Assume that the file looks as follows
Mystic River: 4Lost: 1The Reader: 5Pulp Fiction: 5No Country for Old Man: 5…while ( !moviesFile.eof() ) {
moviesFile.getline(name, 40, ':');
moviesFile >> score;cout << name << ": " << score << endl;
moviesFile.ignore();
}
The loop is execute once, if the file is emptyDoesn’t work!!!
![Page 18: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/18.jpg)
TNCG18(C++): Lec 9 18
Testing with eof()
• moviesFile.eof()– First read then test if end-of-file– If EOF is reached
• getline() and >> give no error• eofbit is set• eof() returns true
![Page 19: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/19.jpg)
TNCG18(C++): Lec 9 19
File Position Pointers
– Number of next byte to read/write– Functions to reposition pointer
• seekg (seek get for istream class)• seekp (seek put for ostream class)• Classes have "get" and "put" pointers
– seekg and seekp take offset and reference position• Offset: number of bytes relative to a reference position• Reference positions (ios::beg default)
– ios::beg - relative to beginning of stream– ios::cur - relative to current position– ios::end - relative to end
![Page 20: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/20.jpg)
TNCG18(C++): Lec 9 20
File Position Pointers• Examples
– fileObject.seekg(0)• Goes to front of file (location 0) because ios::beg is default
– fileObject.seekg(n)• Goes to nth byte from beginning
– fileObject.seekg(n, ios::cur)• Goes n bytes forward
– fileObject.seekg(n, ios::end)• Goes n bytes back from end
– fileObject.seekg(0, ios::end)
• Goes to last byte– seekp similar
![Page 21: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/21.jpg)
TNCG18(C++): Lec 9 21
File Position Pointers
• To find pointer location– tellg and tellplong location;location = fileObject.tellg()
![Page 22: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/22.jpg)
TNCG18(C++): Lec 9 22
Example
• Assume you need to scan a file twice from the beginning
//read file from beginning to EOF…// reset eofbit for next inputfile.clear();
// move to beginning of filefile.seekg( 0 );
//read again file from beginning to EOF…
![Page 23: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/23.jpg)
TNCG18(C++): Lec 9 23
Updating Sequential-Access Files• Updating sequential files
– Risk overwriting other data– Example: change name "White" to "Worthington"
• Old data300 White 0.00 400 Jones 32.87
• Insert new data
– Formatted text different from internal representation
300 White 0.00 400 Jones 32.87
300 Worthington 0.00ones 32.87
300 Worthington 0.00
Data gets overwritten
![Page 24: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/24.jpg)
TNCG18(C++): Lec 9 24
Random-Access Files
• Instant access– Want to locate record quickly
• Airline reservations, ATMs
– Sequential files must search through each one
• Random-access files are solution– Instant access– Insert record without destroying other data
• As if an empty record was previously created
– Update/delete items without changing other data
![Page 25: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/25.jpg)
TNCG18(C++): Lec 9 25
Random-Access Files
• C++ imposes no structure on files– Programmer must create random-access files– Simplest way: fixed-length records
• Calculate position in file from record size and key• What if records are not fixed length?
0 200 300 400 500
byte offsets}
} } } } } }
100
100bytes
100bytes
100bytes
100bytes
100bytes
100bytes
![Page 26: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/26.jpg)
TNCG18(C++): Lec 9 26
Random-Access File vs Text File• "1234567" (char*) vs 1234567 (int)
– char* takes 8 bytes (1 for each character + ‘\0’)– int takes fixed number of bytes (perhaps 4)
• 123 same size in bytes as 1234567
• << operator and write()– outFile << number
• Outputs number (int) as a char*• Variable number of bytes
– outFile.write( const char*, int );
• Outputs raw bytes• Takes pointer to memory location and number of bytes to write
– Copies data directly from memory into file
![Page 27: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/27.jpg)
TNCG18(C++): Lec 9 27
file.write( const char*, int );
int i = 5567;int*p = &i;file.seekp(8);file.write( ( char* ) p , sizeof( int ) );
pint i;
disk fileMain memory
![Page 28: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/28.jpg)
TNCG18(C++): Lec 9 28
Creating a Random-Access File
• ExampleoutFile.write( (char*)( &number ), sizeof( number ) );
– &number is an int*• Convert to char*
– sizeof(number)• Size of number (an int) in bytes
– read function similar (more later)
![Page 29: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/29.jpg)
TNCG18(C++): Lec 9 29
Writing a Binary File with Movies Datatypedef struct {
char name[40];int score;
} Movie;
Movie film;cin.getline(film.name, 40, ':');cin >> film.score;
ofstream moviesDat( "movies.dat", ios::binary )
//exit program if ofstream could not open fileif ( !moviesDat ) {
cerr << "File could not be opened." << endl;return;
}
moviesDat.write((char*)( &film ), sizeof(film));
![Page 30: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/30.jpg)
TNCG18(C++): Lec 9 30
Writing Data Randomly to a Random-Access File
• Use seekp to write to exact location in file– Where does the first record begin?
• Byte 0
– The second record?• Byte 0 + sizeof(object)
– Any record?• (Recordnum - 1) * sizeof(object)
– Example: write a new movie data on the ith position
moviesData.seekp( (i-1) * sizeof( Movie ) );moviesDat.write((char*)( &film ), sizeof(film));
![Page 31: Lecture 9 - Linköping Universitywebstaff.itn.liu.se/~aidvi/courses/07/C++/lectures/lec9.pdf6 7 TNCG18(C++): Lec 9 3 Files and Streams • When file opened –A stream object associated](https://reader036.vdocuments.us/reader036/viewer/2022062608/609ff095763b181e9d772c6c/html5/thumbnails/31.jpg)
TNCG18(C++): Lec 9 31
Reading Data Sequentially from a Binary File
• read - similar to write– Reads raw bytes from file into memory– inFile.read( (char*)( &number ), sizeof( int ) );
• &number: location of the data• sizeof(int): how many bytes to read
– Do not use inFile >> number with raw bytes• >> converts number to text format• e.g. 123 does not occupy same number of bytes as 1234