Positions Within a [File] Stream

An input stream has a position where it is currently reading or getting information — the 'get' position. (An output stream likewise has a 'put' position, but that's another story.) The method tellg() will return to you a streampos value which is the current 'get' position within the stream (relative to the beginning of the file, in particular).

streampos counts byte by byte. Typically a char is a single byte. Except for '\n' which varies in size from system to system. It may be anywhere from 1 to 3 bytes in the file. If you let the stream tell you valid positions, you don't have to worry about how many bytes a newline takes up on the current system. Leave that mumbo-jumbo to the folks who program file transfer protocols. (Setting 'ascii' transfer mode in ftp or sftp will convert line-ending characters during the file transfer.)

The seekg() function will take a streampos value and move the current 'get' position to the desired place within the file stream. The value 0 represents the very beginning of the file — the first position; zero away from/offset from the beginning.

There is a second [optional] argument for seekg() that tells to where the streampos is relative: ios_base::beg, ios_base::cur, or ios_base::end. (The default is beg, as you may have guessed.)

The end of file marker physically counts as position 0 relative to the end of the file. All other positions are negative offsets from there.

The streampos passed relative to the cur position may be either positive or negative...or zero. But may the fates save you if you go too far and exceed the file's allotted space.

Of course, the streampos passed relative to beg (or no specified relative position) should be only zero or positive. Here negatives will get you into trouble!

Positions on cin

Although cin does handle tellg and seekg requests, it doesn't necessarily do so correctly. Mostly cin's tellg results are non-sense. I'm not sure, therefore, what seekg would get you here. Not even 0 works. *sigh*

Re-Processing a File

To re-process a file, do NOT close it and re-open it! This is a huge waste of OS, user, and your time... Instead, make sure the stream is in a good state and then simply 'seek' the 'get' position to the desired position.

Example from Lecture

Here's the example from class, too...