C++ FileIO - Adelphi University

Download Report

Transcript C++ FileIO - Adelphi University

C++ FileIO
pepper
fstream
fstream
From http://www.cs.uic.edu/~jbell/CourseNotes/CPlus/FileIO.html
Using fstream
• Include <fstream>
• Declare variable of type fstream
• Open file – ask your fstream variable to open the file
– Your ofstream var .open(“filename”,qualifiers)
– qualifiers
•
•
•
•
In: ios::in
Out: ios::out
Append: ios::append
Binary: ios::binary
– Ex:
• ofstream myfile;
• myfile.open ("example.bin", ios::out | ios::app | ios::binary);
Test status of stream
– myfile.is_open() : returns true if open
– myfile.eof() : returns true if file at end and open
for reading
– myfile.bad() : return true if any read or write fails
– myfile.good() : opposide of bad
–Ex:
If (myfile.is_open()) {
myfile << “ I can write just like cout “;}
If (!myfile.eof()) { // read more };
Stream positions
Read (Get)
Write (Put)
Where?
tellg
tellp
Set position
seekg (position)
seekp (position)
Set relative position
seekg (offset, direction)
seekp (offset,direction)
directions:
• ios::beg (beginning of file)
• ios::cur (current position)
• ios::end (end of file)
Binary file methods
• binary read and write helper:
– read (buf, size);
– write(buf, size);
• Just makes it easier to use a record layout
(structure)
Close when done
• Ask your stream to close itself:
• myfile.close();