140 likes | 234 Views
Principles of Computer Science I Honors Section. Note Set 4 CSE 1341. Today:. Reading/Writing Character Files. 3 Steps to Using a File. OPEN the file READ from or WRITE to the file CLOSE the file. File Streams in C++. File Streaming Objects Very Similar to cin and cout
E N D
Principles of Computer Science IHonors Section Note Set 4 CSE 1341
Today: Reading/Writing Character Files
3 Steps to Using a File • OPEN the file • READ from or WRITE to the file • CLOSE the file
File Streams in C++ • File Streaming Objects • Very Similar to cin and cout • source and destination is the file, not the console • must be created explicitly, not automatically there like cin and cout • fstream • Can be used to read and/or write to files (bidirectional file I/O)
File Objects • ofstream • Data type that can be used to create files and/or write information to them. • Output File Stream • ifstream • Data type that can be used to read information from files into memory • Input File Stream memory file memory file
Writing to a file fstream can perform bidirectional I/O fstream file; file.open(“data.txt”, ios::out) //check to see if the file is open if(!file.is_open()) { cout << “File not open”; exit(0); } int a = 10, b = 15, c = 20; file << a << b << c; file.close();
Reading from a file fstream file; file.open(“data.txt”, ios::in) //check to see if the file is open if(!file.is_open()) { cout << “File not open”; exit(0); } int a, b, c; file >> a >> b >> c; file.close();
eof • eof == end of file • The way to determine when there is no more data to be read • can be tricky depending on how you are reading the file. • use function eof() member function to check and see if you’ve reached the end of file • useful for reading when you don’t know how much data is in the file
Loop-and-a-Half Pattern while (true) { //read into value if ( value == sentinel ) break; //process value }
Loop-and-a-Half Pattern with Files fstream fIn; fIn.open(“data.txt”, ios::in) if( !fIn ) { exit(0); } int temp; while (true) { fIn >> temp; if (fIn.eof()) break; cout << temp; }
General Functions on File Streams • open(char name[], ios_base::openmode) • opens a file stream • is_open() • returns true if the file was successfully opened • close() • close the file stream • eof() • returns true if the end-of-file has been reached • See text and http://www.cplusplus.com/reference/iostream/fstream for more file stream options
Passing File Streams to Functions • Always Pass By Reference void processFile(fstream&); int main() { fstream fin (“data.txt”, ios::in); processfile(fin); //other stuff } void processFile (fstream& file) { //do some stuff here }
Over the Weekend • Read Chapter 3 Section 3.14 (may have done this already) • Read Chapter 12 Sections 12.1 – 12.5