The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science
Programming Languages and Tools:
CS:3210:0001
Lecture/Lab #17
Programming with C++
File input/output, I/O error checking, string streams
Warm up
-
In your own words, describe the function of a destructor for a user-defined type
-
What will be the output of the following program?
struct point {
point() { std::cout << "ctor\n"; }
~point() { std::cout << "dtor\n"; }
};
point add( point p1, point p2 ) {
return p1 + p2;
}
add( point(0, 0), point(10, 10) );
File input/output
- We already know how to write to/read from a file:
#include <iostream>
#include <fstream>
void hello( std::ostream& out )
{
out << "Hello, world!" << std::endl;
}
int main()
{
hello( std::cout ); // print greeting to console
std::ofstream out( "hello.txt" );
hello( out ); // save greeting to file
}
File input/output (cont.)
-
Use ifstream objects (input-file-stream) to read from a file, ofstream objects (output-file-stream) to write to a file, fstream objects if you need to do both simultaneously.
-
Input/output operators for strings are not symmetric; use getline if you want to read a single line of text from a stream.
I/O error handling
- Input/output operations will fail, so we need to check for errors
- A failed input/output operation sets the stream into a error state
- Once an error has occurred, subsequent I/O operations on that stream will fail
- The easiest way to determine the state of a stream object is to use that object as a condition
s.eof()
s.good()
s.clear()
Returns true if s hit end-of-file
Returns true if s is in a valid state
Reset stream to a valid state
- Operations on the stream state:
I/O patterns
I/O streams hierarchy
#include <ios>
#include <ostream>
#include <istream>
#include <fstream>
#include <sstream>
#include <iostream>
cin, cout, cerr, clog
Programming with C++, Spring 2020, Lecture #17
By Aleksey Gurtovoy
Programming with C++, Spring 2020, Lecture #17
File input/output, I/O error checking, string streams
- 544