ex8-10.cpp - Example 8-10 File I/O - positioning in a file

// File ex8-10.cpp - file I/O

#include <fstream>
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;

int main() 
{
	int ch, i;

	// Open a file for output
	ofstream fout("da_file");
	
	// Check file open
	if (!fout) {
		cerr << "I can't open \"da_file\"\n";
		exit(EXIT_FAILURE);
	}

	// Write 4 lines into the file
	fout << "Have a nice day\n";
	fout << 7 << endl;
	fout << 3.14159 << endl;
	fout << hex << 123 << ' ' << oct << 123 << endl;
	
	// Close the file
	fout.close();
	
	// Open the file for input
	ifstream fin("da_file");
	
	// Check input file open
	if (!fin) {
		cerr << "I can't open \"da_file\"\n";
		exit(EXIT_FAILURE);
	}
	
	char buff[80];

	// Read each line from the file
	while (!fin.getline(buff,80).eof()) {
		// Print the length of the line and its contents
		cout << strlen(buff) << '\t' << buff << endl;
	}
	
	// Print the current position in the file
	cout << fin.tellg() << endl;
	
	// Move to byte 7 (the 8th byte) in the file
	fin.seekg(7,ios_base::beg);
	
	// Print the current position in the file
	cout << fin.tellg() << endl;

	// Set the boooalpha flag for cout
	cout.setf(ios_base::boolalpha);
	
	// Print the file's stream state and state bits
	cout << "fin.rdstate()=" << fin.rdstate();
	cout << " fin.bad()=" << fin.bad();
	cout << " fin.fail()=" << fin.fail();
	cout << " fin.eof()=" << fin.eof() <<endl;
	
	// Clear the stream state
	fin.clear();
	
	// Print the file's stream state and state bits
	cout << "fin.rdstate()=" << fin.rdstate();
	cout << " fin.bad()=" << fin.bad();
	cout << " fin.fail()=" << fin.fail();
	cout << " fin.eof()=" << fin.eof() <<endl;
	
	// Move to byte 7 (the 8th byte) in the file
	fin.seekg(7,ios_base::beg);
	
	// Print the current position in the file
	cout << fin.tellg() << endl;
	
	// Read the next "word" from the file
	fin >> buff;
	
	// Print the "word"
	cout << buff << endl;
	
	// Print the current position in the file
	cout << fin.tellg() << endl;
	
	// Read the next 10 characters
	for (i = 0; i < 10; i++) {
		ch = fin.get();
		// Print counter, char (as int), char, and stream position
		cout << i << '\t' << ch << '\t' << (char) ch << '\t' << fin.tellg() << endl;
	}

	return 0;
}



CIS27: Programming in C++    Instructor: Joe Bentley