Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding streamreader and internalbuffer?

Tags:

c#

I have a .txt file that has 3 lines as following:

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

14

My question is why the position value is 14? why it's not 4 as pointer of the stream would point to '\n' character that is at the end of the first line A50?Is this related to internalbuffer?and what's internalbuffer in detail and how it is work with streamreader?

sorry for bad english.

like image 741
AWT Avatar asked Mar 24 '23 23:03

AWT


1 Answers

The StreamReader reads data from the disk into an internal buffer and then satisfies requests from that buffer.

It works that way in order to reduce the number of times it has to call the operating system for data. If it didn't have an internal buffer, then it would have to do this:

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

With the internal buffer, it reads a big chunk of data (default is something like 4K bytes, but that can be changed) into memory. Then it can quickly scan that block of data for a newline character and return the string.

like image 181
Jim Mischel Avatar answered Apr 10 '23 08:04

Jim Mischel