動力this answer我想知道如果使用大量的FileStream.Seek(-1)
,幕下會發生什麼。FileStream.Seek與緩衝讀取
爲清楚起見,我會重新發布了答案:
using (var fs = File.OpenRead(filePath))
{
fs.Seek(0, SeekOrigin.End);
int newLines = 0;
while (newLines < 3)
{
fs.Seek(-1, SeekOrigin.Current);
newLines += fs.ReadByte() == 13 ? 1 : 0; // look for \r
fs.Seek(-1, SeekOrigin.Current);
}
byte[] data = new byte[fs.Length - fs.Position];
fs.Read(data, 0, data.Length);
}
個人而言,我會像讀2048個字節到緩衝區和搜索的字符該緩衝區。
使用反射器我發現內部方法是使用SetFilePointer。
是否有任何關於Windows緩存和向後讀文件的文檔? Windows緩衝「向後」並在連續使用Seek(-1)
時諮詢緩衝區,還是從當前位置開始預讀?
有趣的是,一方面大多數人都贊同Windows做好緩存,但另一方面,「向後讀取文件」的每個答案都涉及讀取字節塊並在該塊上進行操作。
做一些認真的同行評審吧? – ChaosPandion 2010-12-06 20:05:53
@ChaosPandion:我沒有評價你的評論,我只是好奇。 – VVS 2010-12-06 21:26:55