I need to write a program that reads certain characters in a file.
For example: all characters from beginning to end or in reverse order.
//This program reads a file from beg to end, end to beg, beg to 4th position,
//8th to 15th position, end to 3rd position, and 22nd to end
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char letter; //holds the character
fstream file("alphabet.txt", ios::in);
file.seekg(5L, ios::beg);
file.get(letter);
cout << "Beginning to the 4th letter: " << letter << endl;
file.seekg(-22L, ios::end);
file.get(letter);
cout << "21st letter to the end: " << letter << endl;
file.close();
system("pause");
return 0;
}
Last edited on
If you use seekg(), make sure to open the file in binary mode.
However, you should better read the file into a string and index that.
Hope this helps.
What do you mean read the file into a string and index?