/////////////////////////////////////////////////////////////// // readwrit.cpp - demonstrate read/write fstreams // // with buffer location seeking // // Jim Fawcett, 24 Mar 96, modified 23 Mar 97 // /////////////////////////////////////////////////////////////// #include // cout, << #include // ifstream(), <<, >> #include // exit(1); using namespace std; void main(int argc, char *argv[]) { if(argc < 2) { cout << "please enter file name on command line\n"; exit(1); } /////////////////////////////////////////////////////////////// // file open modes: in out app ate // // nocreate noreplace trunc // /////////////////////////////////////////////////////////////// // save input file as a temporary file for reading and writing ifstream masterin(argv[argc-1]); ofstream tempout("tmp.tmp"); tempout << masterin.rdbuf(); masterin.close(); tempout.close(); // open temporary for processing ifstream in("tmp.tmp", ios::in|ios::out); if(!in.good()) { cout << "can't open file tmp.tmp" << endl; exit(1); } // use input buffer for output too ostream out(in.rdbuf()); // now, try reading and writing cout << "\nthis is a test file for reading and writing:\n" << "============================================\n"; cout << in.rdbuf(); out << "this line is added to the end\n"; // how many bytes in file? streampos sp = out.tellp(); out.seekp(-sp, ios::end); // back up from end out << "this overwrites first\n"; // write it out to see what happened cout << "\n\nmodified file:\n" << "==============\n"; in.seekg(ios::beg); // go to beginning cout << in.rdbuf(); }