I need a little help with this :icon_redface:
if I use ifstream::read() and go past the end of the file, how do I tell how many chars have been read?
Guess you are looping until eof?
Every loop count an integer one up.
After the loop, you just multiply the count integer with the amount of bytes read per read call (probably 1? ;))
I'm not sure if it is better or worse, but I like this method much more:
std::ifstream stream; ... stream.seekp(0, std::ios::end); // find eof size_t size = stream.tellp(); // this actually provides the real size stream.seekp(0); // find start char* buffer = new char[size]; // allocate space stream.read(buffer, size); // read it all in at once stream.close(); // done :D
Note: seekp and tellp may be seekg and tellg.
Can't remember whether p or g version is for ifstream.
Actually, I'm reading in 1024 byte chunks, and sending the 1024 bit buffer over winsock each read, so I need a way to communicate how many characters the last buffer actually holds, if not the entire 1024 bytes
Then I'm not really sure of a good way to do that (as in non-hacky).
I believe the C way of reading returns a variable with bytes read, but that's no help in C++.
If you can't use the way I suggested (i editted the post, if you haven't noticed), then I'm not sure.
I think I may have found it. If I call tellg() before I read, I can call tellg again after I read and subtract to fine the bytes read.
thanks for the help =D
if you are using read() to read the data, then immediately call gcount() to get the number of bytes that were read. tellg() will only tell you where the file pointer is, not how many bytes were read.
Learnt something new today, not bad :D
Also he didn't assume tellg would get the number of bytes, but by subtracting the old tellg with the new, you get the number read.
Of course gcount() is preferable.
I have to go with Ancient though...I tried using tellg(),but tellg() reads -1 once you have read past the end of the file, because it returns the next char that will be read, not the last one that was read, which of course doesn't exist after EOF =(
thanks again, gcount() is exactly what I needed =)
We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.