C++ examples for File Stream:File Operation
Using peek( ), unget( ), and ignore() to read file
#include <iostream> #include <fstream> #include <cctype> using namespace std; int main()//from w w w .j av a2 s.co m { char ch; char idnum[5]; // Null-terminate idnum so that it can hold a char * string. idnum[4] = 0; // Create an ofstream object and attempt to open the file test.dat. ofstream fout("test.dat"); // Verify that the file has been successfully opened. if(!fout) { cout << "Cannot open test.dat for output.\n"; return 1; } // Write some information to the file. fout << "Tom #1111\nRalph #1234\nTed #2222\n"; fout << "Holden #pending\nJones, #8888\n"; // Close the output file. fout.close(); if(!fout.good()) { cout << "Error creating data file."; return 1; } // Attempt to open the test.dat file. ifstream fin("test.dat"); if(!fin) { cout << "Cannot open test.dat for input.\n"; return 1; } // Use exceptions to watch for errors. fin.exceptions(ios::badbit | ios::failbit); try { // Find and display all ID numbers: do { // Find the start of an ID number. fin.ignore(40, '#'); // If the end of the file is encountered, stop reading. if(fin.eof()) { fin.clear(); // clear eofbit break; } ch = fin.peek(); if(isdigit(ch)) { fin.read((char *)idnum, 4); cout << "ID #: " << idnum << endl; } else { cout << "ID not available: "; ch = fin.get(); while(isalpha(ch)) { cout << ch; ch = fin.get(); }; fin.unget(); cout << endl; } } while(fin.good()); } catch(ios_base::failure exc) { cout << "Error reading data file.\n"; } try { fin.close(); } catch (ios_base::failure exc) { cout << "Error closing data file."; return 1; } return 0; }