Search code examples
c#fileparsingstream

How to peek the n-th char in stream reader c#


I am making a custom input reader for a parser in C#, and I am trying to peek the n-th character from a stream reader without moving the streams position, so that when the function is called multiple times I get the same output (like the inbuilt peek function).

I can currently get the n-th element, as seen in code below, however in doing this I move the streams position and so each call I get a different char.

private StreamReader _reader;
private int _peekChar = -1;

public InputReader(Stream inputStream)
{
    _reader = new StreamReader(inputStream);
}

//  Returns the next character in the input stream without consuming it
public char Peek()
{
    // Checks if character already peeked
    if (_peekChar == -1)
        _peekChar = _reader.Peek();

    return (char)_peekChar;
}

//  Returns the n th next character in the input stream without consuming it
public char Peek(int n)
{
    if (n <= 0)
        throw new ArgumentException("n must be a positive integer.");

    char[] buffer = new char[n];
    int bytesRead = _reader.Read(buffer, 0, n);

    if (bytesRead < n)
        throw new EndOfStreamException("Not enough characters in the stream to peek.");

    return buffer[n - 1];
}

Given I call Peek(1) 3 times on a stream with "<HTML> <p> test <p/> <HTML/>" I expect 3 outputs of <, however I get < H T


Solution

  • When you

    _reader.Read(buffer, 0, n);

    Then the stream's position is increased.

    You need to move the stream's position back after reading (if the stream supports it)

    _reader.Seek(-bytesRead, SeekOrigin.End);