file pointer, positioning from end

Hi -

I need to write a utility that will extract values from the last 256 lines of a large file. Each line will look like this:

NN XXXXXXXX XXXXXXXX

I need to pick up the two hex values represented by the XXXXXXXX above.

What's the easiest way to position to the end of the file, then move back by (256 * 3) tokens?

Thanks.
I read that page...I know how to position to the end of the file. I was hoping someone knew of a way to move backwards in the file by more than a character-by-character basis.
So...are you suggesting that, since I know the length of each record in the file, I calculate how far back to go, and just position directly there?

I was hoping to move backwards by lines or tokens, but I suppose I can do it by characters.
Basically. If there's a way to move backwards by tokens, or by lines, I'm not aware of what it is.
I implemented a down-and-dirty fix for this:

1
2
3
4
5
6
7
8
9
10
11
12
void	openFile (ifstream& f)
{
	const	long	LINE_LEN = 23;
	int	pos;
// position to 256 lines before end of file

	f.open("demodoutcarr.txt");
	f.seekg(0, ios::end);
	pos = f.tellg();
	pos -= LINE_LEN * NBR_RECORDS;
	f.seekg(pos);
}


But just ran into a snag: because Windows uses a CR/LF as a line terminator, and the Mac uses a LF, my line lengths are different between the two. Any suggestions for a cleaner way to do this? This is what I've come up with, but I'm kind of "meh" on it:

1
2
3
4
5
#ifdef __APPLE__
	const	long	LINE_LEN = 23;
#elif _WIN32
	const	long	LINE_LEN = 24;
#endif 
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
std::deque<char> txt;
std::ifstream f ("file.txt", ios::in|ios::ate/*AT End*/);
unsigned at (f.tellg());
unsigned lines (0);
while(f && lines <= 256)
{
    f.seekg(--at);
    txt.push_front(char(f.get()));
    if(txt.front() == '\n') ++lines; //next may be \r but it does not matter
}
std::string text (txt.size(), '\0');
std::string::iterator st = text.begin();
for(std::deque<char>::iterator it = txt.begin(); it != txt.end(); ++it, ++st) *st = *it;
I don't know if this works, give it a try.
Topic archived. No new replies allowed.