|
ex8-11.cpp - Example 8-11 File I/O - positioning, modes, and stream state |
// File ex8-ll.cpp
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
void print_file(istream&);
int main() {
// Declare and open an output file stream
ofstream fout("da_file");
// Check the file open
if (!fout) {
cerr << "I can't open \"da_file\"\n";
exit (EXIT_FAILURE);
}
// write 3 lines into a new file
fout << "Have a nice day.\n";
fout << "Have a great day.\n";
fout << "Have a totally excellent day.\n";
// close the file
fout.close();
// re-open the file as an fstream object for input and output
fstream finout("da_file",ios_base::in|ios_base::out);
print_file(finout);
// clear the EOF bit
finout.clear();
// position to byte 7 in the file
finout.seekp(7,ios::beg);
// Are the get and put pointers the same?
cout<< "finout.tellg()=" << finout.tellg()<< endl;
cout<< "finout.tellp()=" << finout.tellp()<< endl;
// replace "nice" with "fine"
finout<< "fine";
// Are the get and put pointers still the same?
cout<< "finout.tellg()="<< finout.tellg()<< endl;
cout << "finout.tellp()=" << finout.tellp() << endl;
print_file(finout);
// close the file
finout.close();
// reopen the file in input/output/binary mode
finout.open("da_file",ios_base::in|ios_base::out|ios::binary);
// write hey into the file
finout<< "hey";
print_file(finout);
// try again to write hey into the file
finout.seekp(0,ios::beg);
finout<< "hey";
print_file(finout);
// try app mode
finout.clear();
finout.close();
finout.open("da_file",ios_base::in|ios_base::out|ios::app);
finout<< "hey";
print_file(finout);
return 0;
}
void print_file(istream& file)
{
cout<< "file.rdstate="<< file.rdstate() << endl;
char buffer[80];
file.seekg(0,ios::beg);
while (file.getline(buffer,sizeof(buffer))) {
cout<< buffer << endl;
}
cout << endl;
}
CIS27: Programming in C++ Instructor: Joe Bentley