This is a simple example of how to make use of seekg and
tellg member functions from the
basic_istream class to allow random access within a file
stream. Though not shown in this example, these member functions work for
basic_ostream objects as well.
1// randomAccess.cpp
2// Asks user for a filename and word. It then displays the number of
3// lines containing the word and then displays each line.
4// t a y l o r@msoe.edu, 9-18-2002
5// Modified: t a y l o r@msoe.edu, 9-19-2002 removed extraneous fin.get() call
6
7#include <iostream>
8#include <fstream>
9#include <string>
10#include <list>
11
12using std::cout;
13using std::string;
14using std::streampos;
15using std::getline;
16
17int main()
18{
19 string filename="driver.cpp";
20 string word="string";
21 cout << "Please enter the name of a file: ";
22 std::cin >> filename;
23 cout << "Please enter a word you would like to find: ";
24 std::cin >> word;
25
26 std::ifstream fin(filename.c_str());
27 string line;
28 streampos currentPosition = fin.tellg();
29 std::list<streampos> linePositions;
30
31 while(getline(fin, line)) {
32 if(string::npos!=line.find(word)) {
33 linePositions.push_back(currentPosition);
34 }
35 currentPosition = fin.tellg();
36 }
37
38 // We need to clear the error flag that was set when we tried
39 // to read past the end of the file.
40 fin.clear();
41
42 cout << "There are " << linePositions.size() << " lines containing "
43 << word << ".\nThey are:\n";
44
45 std::list<streampos>::const_iterator itr;
46 for(itr = linePositions.begin(); itr!=linePositions.end(); ++itr) {
47 fin.seekg(*itr);
48 getline(fin, line);
49 cout << line << "\n";
50 }
51
52 return 0;
53}