Return last value in document??

How would I go about trying to fetch the last value in a document? Assuming I have have already called and opened the document with a stream. Could I use something like:

1
2
3
4
5
6
7
8
9
10
11
// get length of file:
  is.seekg (0, ios::end);
  length = is.tellg();
  is.seekg (0, ios::beg);

  // allocate memory:
  buffer = new char [length];

  // read data as a block:
  is.read (buffer,length);
 cout << buffer[length] << endl; // Would this display the last block in the array??? 

I have tried this and it's not working. I would think it would work though...any ideas?
Well if the buffer is of size 'length', then [length-1] would be the last entry. [length] is actually out of bounds.

But even that might not work. If the file is opened as "text" (the default) then it screws up offsets and file positions because line breaks are "translated".

I don't know who thought "text mode" was a good idea but I really want to slap them.

Solutions would be to open in binary mode and do the above code (after the length-1 fix), or only read the last character instead of the whole file:

1
2
3
is.seekg (-1, ios::end);  // seek to one before the end

cout << is.get() << endl;  // <- output the last value 

Topic archived. No new replies allowed.