Tuesday, November 12, 2013

Random Access data in C++

In C++'s I/O system, you perform random access by using the seekg() and seekp() functions. Their most common forms are:

istream &seekg(off_type offset, seekdir origin);
ostream &seekp(off_type offset, seekdir origin);

The following program demonstrates the seekp() function. It allows you to change a specific character in a file. Specify a filename on the command line, followed by the number of the character in the file you want to change, followed by the new character. Notice that the file is opened for read/write operations.

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main(int argc, char *argv[])
{
if(argc!=4) {
cout << "Usage: CHANGE <filename> <character> <char>\n";
return 1;
}
fstream out(argv[1], ios::in | ios::out | ios::binary);
if(!out) {
cout << "Cannot open file.";
return 1;
}
out.seekp(atoi(argv[2]), ios::beg);
out.put(*argv[3]);
out.close();
return 0;
}

The next program uses seekg() . It displays the contents of a file beginning with the location you specify on the command line.#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main(int argc, char *argv[])
{
char ch;
if(argc!=3) {
cout << "Usage: SHOW <filename> <starting location>\n";
return 1;
}
ifstream in(argv[1], ios::in | ios::binary);
if(!in) {
cout << "Cannot open file.";
return 1;
}
in.seekg(atoi(argv[2]), ios::beg);
while(in.get(ch))
cout << ch;
return 0;
}

No comments:

Post a Comment