How to read a text file reversely with iterator in C#

后端 未结 11 1872
甜味超标
甜味超标 2020-11-22 04:05

I need to process a large file, around 400K lines and 200 M. But sometimes I have to process from bottom up. How can I use iterator (yield return) here? Basically I don\'t l

11条回答
  •  忘了有多久
    2020-11-22 04:30

    To create a file iterator you can do this:

    EDIT:

    This is my fixed version of a fixed-width reverse file reader:

    public static IEnumerable readFile()
    {
        using (FileStream reader = new FileStream(@"c:\test.txt",FileMode.Open,FileAccess.Read))
        {
            int i=0;
            StringBuilder lineBuffer = new StringBuilder();
            int byteRead;
            while (-i < reader.Length)
            {
                reader.Seek(--i, SeekOrigin.End);
                byteRead = reader.ReadByte();
                if (byteRead == 10 && lineBuffer.Length > 0)
                {
                    yield return Reverse(lineBuffer.ToString());
                    lineBuffer.Remove(0, lineBuffer.Length);
                }
                lineBuffer.Append((char)byteRead);
            }
            yield return Reverse(lineBuffer.ToString());
            reader.Close();
        }
    }
    
    public static string Reverse(string str)
    {
        char[] arr = new char[str.Length];
        for (int i = 0; i < str.Length; i++)
            arr[i] = str[str.Length - 1 - i];
        return new string(arr);
    }
    

提交回复
热议问题