Understanding stream and internal buffer?

I have a .txt file with three lines:

A50

B25

C25

This is my code:

FileStream fs = new FileStream(@"E:\1.txt", FileMode.Open); StreamReader sr = new StreamReader(fs); textBox1.AppendText(sr.ReadLine() + "\r\n"); textBox1.AppendText(fs.Position.ToString()); 

now after running the above code the output will be:

A50

fourteen

My question is: why is the position value equal to 14? why is it not 4, because the stream pointer points to the character "\ n", which is located at the end of the first line of the A50? Is this related to the internal buffer? and what is the internal buffer in detail and how does it work with streamreader?

sorry for bad english.

+4
source share
2 answers

My question is: why is the position value equal to 14?

StreamReader has "overread" to perform relatively few read operations on the underlying stream. Yes, this is due to the internal buffer - the idea is that it will perform “short” read operations in the base stream, often reading more than necessary to satisfy the current operation, thereby preventing many single-byte reads.

To read a line at a time without over reading it, it would have to read one byte at a time, which might even be more than one character. Depending on the implementation of the thread, this may be inefficient. Instead, it reads into the buffer, which is the hidden implementation part (you do not have direct access to the buffer), and then satisfies requests from this buffer until it is read from the stream again.

+3
source

StreamReader reads data from the disk into the internal buffer and then satisfies requests from this buffer.

It works in such a way as to reduce the number of times it should call the operating system for the data. If he did not have an internal buffer, then he would have to do this:

 while (not end-of-file and character != newline) { read next character and append to string } 

With an internal buffer, it reads a large chunk of data (by default it is about 4 KB, but can be changed) into memory. He can then quickly scan this data block for a newline and return a string.

+3
source

Source: https://habr.com/ru/post/1480558/


All Articles