What I want to do is, send a file 8kB at a time. (Without filling RAM with full file)
This is my Code:
while ( file.good()){
file.readsome(sinLine,8000);
client.saveFile(_return, std::string(sinLine), file_name);
}
file is a std::ifstream
for a text file.
client is a thriftClient
, (I don't know how relevant that is, to the problem)
sinLine
is a char * [8000]
The problem is that the recieved file is 242.2kB and the sent file is 142.6kB.
In the debugger I noticed that it went through the loop more than 18 times (142 / 8 = 17.25), but it doesn't go on forever(I don't know exactly how many times, but it's probably 242 /8 times).
I also noticed that every third loop (3, 6, 9...) the value of sinLine
wasn't showing in my IDE (QtCreator).
So my questions are, how does readsome()
work? and am I using it right? or should I be using a different function? or is maybe the conversion from char * to std::string
not correct?
The function readsome()
is fairly useless and probably doesn't do what you are hoping for. It determines the number of guaranteed to be available characters by calling in.rdbuf()->in_avail()
which itself calls the virtual
function showmanyc()
. The default implementation of this function is to return the number of characters known to be the in the buffer (i.e. egptr() - gptr()
on the std::streambuf
). The function then carries on to simple read()
that many characters using in.rdbuf()->sgetn(buffer, n))
.
Note that you can use in.gcount()
to determine how may characters were actually read but the last unformatted input function. That's giving you a better count of characters read than determining the number of characters up to the next null character. Especially as the unformatted input functions make no attempt to null terminate the read data.
Also, your check is for file.good()
isn't great: assuming you go unlucky and the last successful read ends exactly at the last element, the last input will be processed twice. I would strongly recommend using a loop more like this:
for (char buffer[8196]; file.read(buffer, sizeof(buffer)); ) {
client.saveFile(_return, std::string(buffer, buffer + file.gcount()), file_name);
}