Search code examples
haskellghci

Why does Haskell NoBuffering option still seem to buffer?


I loaded up a file in ghci with the following:

h <- openFile "somefile.txt" ReadMode
hSetBuffering h NoBuffering

I then modified and saved somefile.txt in a text editor. When I call hGetChar several times in ghci, I receive the old characters of the file (as if the entire file was buffered when I opened it). I expected to calls of hGetChar to return the modified contents. Why is this not the case?

Edit: The reason why it isn't showing the modified contents in the case decribed above is indeed because of the text editor. When the cat command is used instead (cat > somefile.txt), then the modified file contents is returned.

However, it does still seem to doing buffering. Say the file contents is as follows:

ABCDEFGHI
123456789

If I run hGetChar I get the 'A' as expected.

Now if I use cat (cat > somefile.txt) to change the contents to the following, and run hGetChar again, I would expect 'Z' but it's returning 'B':

AZZZZZZZZ

Solution

  • BufferMode is only relevant when writing to a handle, not when reading from it.

    From [note Buffered Reading] in GHC.IO.Handle.Types:

    Note that the buffering mode (haBufferMode) makes no difference when
    reading data into a Handle.  When reading, we can always just read all
    the data there is available without blocking, decode it into the Char
    buffer, and then provide it immediately to the caller.
    

    The documentation for input BufferMode seems to be outdated.