180 likes | 187 Views
Learn how to manipulate files, strings, and streams efficiently using advanced I/O techniques in C++. Manage input and output streams, open and close files, and control formatting with precision in your programs.
E N D
File I/O Streams, files, strings
Basic Streams • You have already used I/O streams for console input/output • cin >> command; • cout << “The answer is “ << x; • I/O streams also have state, and can be cast to boolean type • while (cin >> command) ...
IO Classes • Already used header <iostream> • cin, cout, cerr, clog • Reads/writes from/to a stream • Header <fstream> • Reads/writes from/to a file • Header <sstream> • Reads/writes from/to a string
IO Classes • Header <iostream> • istream, wistream – read from a stream • ostream, wostream – write to a stream • iostream, wiostream - both • The 'w' is for wide chars • 16-bit character sets • wcin, wcout, wcerr, wclog
IO Classes • Header <fstream> - file access • ifstream, wifstream – read from a file • ofstream, wofstream – write to a file • iofstream, wiofstream - both • Header <sstream> - string access • istringstream, wistringstream - read • ostringstream, wostringstream – write • stringstream, wstringstream - both
IO Objects • No copy or assignment of IO objects • Can't have a parameter or return type that is IO object • Pass & return stream via references • Reference can't be const • Reading or writing changes object state as side-effect
IO Condition State Stream s s.eof() - test end of stream s.fail() - test for fail or badbit fail – recoverable error s.bad() - test for badbit s.good() - test for valid state s.clear() - reset to valid state
Managing Output Buffer • Output Stream cout • Writes are generally buffered by OS for efficiency • To flush output: cout << “Bye!” < endl; // newline cout << “Enter choice: ” << flush; // just flush cout << “mystring” << ends; // null • Buffers are NOT flushed on crash!
unitbuf Manipulator • Output Stream os • If always want stream flushed, os << unitbuf; /* all writes are flushed immediately */ os << nounitbuf; // turn off unitbuf • Looks like pushing data into stream, but really telling stream to perform an action (like flush did)
File I/O • Special operations to open and bind file streams: #include <fstream> fstream fstrm; // unbound fstream fstrm(fname); /* creates and opens file fname in default mode. fname a string or C-style char array */ fstream fstrm(fname, mode); /* uses specific mode */
File Open Modes #include <fstream> in Open for input (not ofstream) out Open for output (not ifstream) app Append (not with trunc) leave data ate Seek to end when opened trunc Truncate the file (only with out) binary Do I/O operations in binary mode ate and binary compatible for any file stream type and with any other mode Default modes are in for ifstream, out for ofstream, and both in and out for fstream.
File Open and Close • Files have session semantics – must open, then use, then close ifstream inStrm(inFile); // open and bind ofstream outStrm; // not bound outStrm.open(inFile + “.bak”) // open method if (inStrm) … // open succeeded if (outStrm) … // open succeeded while (inStrm >> word) … /* fails if eof … or if no match! */ inStrm.close(); // close input stream outStrm.close(); // ditto for output
Formatting Manipulators • May want to control number of decimals in output of double double balance = 12345.67; // car loan double interestRate = 0.065/12; double interest = balance * interestRate; cout << “Interest is ” << interest << endl; • Outputs Interest is 66.8724 (Interest value is 66.872379167 ...)
Formatting Manipulators • Use fixed and setprecision(n) manipulators double balance = 12345.67; // car loan double interestRate = 0.065/12; double interest = balance * interestRate; cout << “Interest is ” << fixed << setprecision(2) << interest << endl; • Outputs Interest is 66.87
Formatting Manipulators #include <iostream> setprecision(n) sets fp precision sets number of significant figures to n default is 6 sigfigs after fixed, n is digits after decimal point fixed displays fp in fixed pt form showpoint show trailing zeros setw(width) sets width of print field left left justifies output right right justifies output Effects persist until state changed by another manipulator
String Streams • Can do parsing operations, etc. on strings • getline from file or cin, then parse #include <sstream> sstream sstrm; // unbound sstream sstrm(s); /* creates stream and copies string s into it */ sstrm.str(); // returns string held sstrm.str(s); /* copies string s into sstrm, returns void */
Example string line, phone; /* hold input vector<PersonInfo> friends; // name, numbers while (getline(cin, line) { // get a line PersonInfo record; // new record istringstream currentLine(line) // bind currentLine to line currentLine >> record.name; // read name while (currentRecord >> phone) { // read next phone number record.phones.push_back(phone); // store friends.push_back(record); // add friend
Note on File Use • May have to convert string to C-style char array for file open to work • Using getline best, since it discards newline at end of line – can delay eof status and cause “repeats” • Move input line to stream for parsing