I want to read 8byte chunks from a binary file at a time till I reach end of the file. Why doesn’t this code work? What are the alternatives?
// read a file into memory
#include <iostream>
#include <fstream>
using namespace std;
int main () {
long long int * buffer;
ifstream is;
is.open ("test.txt", ios::binary );
// allocate memory:
buffer = new long long int;
// read data:
while(!is.eof())
is.read (buffer,sizeof(long long int));
is.close();
delete[] buffer;
return 0;
}
If I replace all long long int with char, the code works perfectly.
Ref: code adapted from http://www.cplusplus.com
The problem is !eof: it tells you whether the last operation hit eof, not whether the next will, and not whether the last failed!
Test the stream’s truthiness itself (or use the fail method which is the same thing, negated), after doing the IO:
Additionally, you don’t have to use new at all:
Your source, cplusplus.com, also fails to check whether the read succeeded before using the data. In general, I find that site great for listing parameters, methods, etc. and horrible for most else.
Putting it all together, with some example output: