I have been trying to understand buffering as much as possible in C++ (it's amazingly confusing) for a Serial I/O program I'm writing. I originally wasn't flushing my output commands (due to ignorance), so instead I looked up here (How to disable buffering on a stream?), and it said to do it through my_fstream.rdbuf()->pubsetbuf(0,0)
before any I/O operation has happened. This seemed to improve my performance, but not fix it entirely... I kept looking for answers and found these two questions: Unbuffered I/O is not working, Unbuffered output with cout, which both say to use my_fstream.setf(std::ios::unitbuf);
instead. This worked much better, but neither of those answers explained why it works better than my_fstream.rdbuf()->pubsetbuf(0,0)
.
Shouldn't they be doing the same thing? Can someone explain to me the difference?
Here's the code I'm testing this on (the device replies to an input of "Start" when it receives it by sending "Ready\r\n" back):
int main(){
std::fstream my_file;
my_file.rdbuf()->pubsetbuf(0, 0);
// my_file.setf(std::ios::unitbuf); // Uncomment this line for testing both cases
my_file.open("/dev/cu.usbmodem14201");
my_file << "Start";
std::this_thread::sleep_for(std::chrono::seconds(10));
}
By the time I reach my sleep, there is no output yet (I need to wait the 10 seconds to see it) unless I uncomment the commented line.
I can confirm messages are received by running a separate python program:
with open("/dev/cu.usbmodem14201", "rb") as f:
for line in f:
print(line)