anonymous1126
anonymous1126

Reputation: 5

Need help using 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. How can I show all characters instead of just one?

//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;

}

Upvotes: -1

Views: 327

Answers (1)

Thomas Matthews
Thomas Matthews

Reputation: 57749

The brute force method is to use a loop for reading all the characters in a file, from font to back:

char c;
while (my_file >> c)
{
  // Do some stuff
}

There is no need to adjust the file position pointer because the read functions automatically advance the file position based on the quantity of characters that are read. Cool feature!

Reading a file from back to front is a waste of time and effort on your part and the OS's. Everything is optimized to read from front to back, so you will be going against the flow.

The algorithm would be:

Open file in binary (to avoid translations)  
Seek to the end position less one.  
Save the position.  
While file position is not at beginning do:  
    Decrement your position variable.
    Seek to the position.
    Read a character
    Process character
    End-While

A better method to reverse the ordering of characters in a file is to read the entire file into memory, then write the memory to a new file in reverse order. The issue here is whether your program is given enough memory to read the entire file.

Upvotes: 0

Related Questions