In text files we use in separationterminatio

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: cified after the name of the file: ofstream of1(name1); // defaults to ios_base::out // defaults ifstream if1(name2); // defaults to ios_base::in defaults ofstream ofs(name, ios_base::app); // append rather than overwrite ofstream append fstream fs("myfile", ios_base::in|ios_base::out); // both in and out fstream both in Stroustrup/Programming 14 Text vs. binary files Text 123 as characters: 1 2 3 ? ? ? ? ? 12345 as characters: 1 2 3 4 5 ? ? ? 123 as binary: 123 12345 as binary: 12345 In binary files, we use In sizes to delimit values sizes 123456 as characters: 1 2 3 123 456 as characters: 1 2 3 4 5 6 4 5 ? In text files, we use In separation/terminatio separation/terminatio n characters 6 Stroustrup/Programming 15 Text vs. binary Text Use text when you can You can read it (without a fancy program) You can debug your programs more easily Text is portable across different systems Most information can be represented reasonably as text Use binary when you must E.g. image files, sound files Stroustrup/Programming 16 Binary files Binary int main() // use binary input and output // use { cout << "Please enter input file name\n"; string name; cin >> name; ifstream ifs(name.c_str(),ios_base::binary); if (!ifs) error("can't open input file ", name); // note: binary // note: cout << "Please enter output file name\n"; cin >> name; ofstream ofs(name.c_str(),ios_base::binary); // note: binary // note: if (!ofs) error("can't open output file ",name); if // “binary” tells the stream not to try anything clever with the bytes // “binary” Stroustrup/Programming 17 Binary files Binary vector<int> v; // read from binary file: // read int i; while (ifs.read(as_bytes(i),sizeof(int))) v.push_back(i); // note: reading bytes // note: // … do something with v … // do // write to binary file: // write for(int i=0; i<v.size(); ++i) ofs.write(as_bytes(v[i]),sizeof(int)); return 0; // note: writing bytes // note: } // for now, treat as_bytes() as a primitive // as_bytes() Stroustrup/Programming 18 Positioning in a filestream Positioning Put position: Get position: 2 0: 6 1: A file: y fstream fs(name.c_str()); … // open for input and output // open // … // fs.seekg(5); // move reading position (‘g’ for ‘get’) to 5 (the 6 th character) // move char ch; fs>>ch; // read and increment reading position // read cout << "character[6] is " << ch << '(' <...
View Full Document

This note was uploaded on 02/18/2012 for the course CSCE 121 taught by Professor Walter daugherity during the Fall '09 term at Texas A&M.

Ask a homework question - tutors are online