C++ istream::read and gcount
A fixed-size read that reaches the end early leaves the stream in a failed state. gcount reports the bytes extracted.
A simple example
istream::read and gcount
- Start with One available byte
- Do this Try to read a complete two-byte field
- Result One byte is missing
Syntax
input.gcount()
Run these examples in C++
Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lessonRead a stock count from a short record
A stock scanner sends each count as a four-byte integer. A transfer stops after two bytes, so the receiver must request the record again before posting the count to inventory.
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::istringstream input(std::string("\0\5", 2));
char record[4];
input.read(record, sizeof record);
if (input.eof() && input.gcount() < 4) {
std::cout << "Request the complete record\n";
}
return 0;
}
Request the complete record
The two-byte transfer falls short of the four bytes required for a stock count.
Decode a complete gate count
A counter sends one four-byte record for the entrance. The device format requires a four-byte integer. Request another transmission if the input ends before all four bytes arrive.
Detect a cut-off meter record
A sensor connection closes after the first two bytes of a four-byte record. The device format requires a four-byte integer. Request another transmission if the input ends before all four bytes arrive.
What to watch for
Only decode the integer after receiving the whole record.