1 / 18

File I/O

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>

cborges
Download Presentation

File I/O

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. File I/O Streams, files, strings

  2. 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) ...

  3. 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

  4. 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

  5. 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

  6. 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

  7. 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

  8. 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!

  9. 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)

  10. 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 */

  11. 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.

  12. 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

  13. 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 ...)

  14. 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

  15. 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

  16. 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 */

  17. 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

  18. 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

More Related