Skip to content

Commit

Permalink
Fix snippet buffered read logic
Browse files Browse the repository at this point in the history
The snippet generates a file with 215 bytes.
It reads the file with a 1024 byte buffer.
While this works with a new 0-initialized buffer, the buffered reading misses using the returned read bytes count.
A file with > 1024 bytes will reuse the now non-0 buffer and print unintended values.

Fix buffered reading to be technically correct and work for arbitrary file contents.

Fixes dotnet#4141
  • Loading branch information
Kissaki committed Oct 22, 2022
1 parent 459da22 commit 27c9283
Showing 1 changed file with 4 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public static void Main()
AddText(fs, "\r\nand this is on a new line");
AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n");

for (int i=1;i < 120;i++)
for (int i = 1; i < 120; i++)
{
AddText(fs, Convert.ToChar(i).ToString());
}
Expand All @@ -35,9 +35,10 @@ public static void Main()
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b,0,b.Length) > 0)
int readLen;
while ((readLen = fs.Read(b, 0, b.Length)) > 0)
{
Console.WriteLine(temp.GetString(b));
Console.WriteLine(temp.GetString(b, 0, readLen));
}
}
}
Expand Down

0 comments on commit 27c9283

Please sign in to comment.