Help with seekg()

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?
Load the entire file into a string, and close the file.

1
2
string s, temp;
while (getline( file, temp )) s += temp + '\n';


Then, if you want to know what the third character in the file is, check the third character in the string.

 
cout << "The fourth letter is: '" << s[ 3 ] << "'.\n";

Hope this helps.
Topic archived. No new replies allowed.