0
Can anyone please tell me usages of Flush of stream Buffer?
I did some research. I came to know that the complier makes a temporary file before outputting to the output stream (in my case, my display). However, the idea seems quite vague to me. I was working on example; here it is file.write(reinterpret_cast<char *>(&r1), sizeof(r1))<<flush; //this is the line of code. Every data is appended the way it is meant to when I use this. file.write(reinterpret_cast<char *>(&r1), sizeof(r1)); //when I don't use flush, it shows me last the inputs, almost like rewrites it, without showing me the whole data in the file.
1 Respuesta
+ 1
The idea is simply that I/O is sloooooow.
If you want to send a letter to the screen, you have to make a system call - that means, talk to the kernel of the operating system. The system will switch to kernel mode so it has unrestricted access to hardware, before it can print the letter.
That takes time. If you write to a file it's even worse because in addition to the syscall you have to write to a hard drive which is very slow.
As a result some of the output is buffered and sent in batches, to reduce the number of syscalls. Because RAM is fast!
Usually you don't have to flush by hand, and closing a file for example flushes it beforehand aswell. In rare cases it may be needed though.
You should never be able to "overwrite" data this way, in the worst case you lose what's in the buffer and not flushed yet.