检查文件结束条件

对于大多数其他语言的标准 I / O 库的做法有点违反直觉,Haskell 的 isEOF 不需要你在检查 EOF 条件之前执行读操作; 运行时会为你做。

import System.IO( isEOF )

eofTest::Int -> IO ()
eofTest line = do
    end <- isEOF
    if end then
        putStrLn $ "End-of-file reached at line " ++ show line ++ "."
    else do
        getLine
        eofTest $ line + 1

main::IO ()
main =
    eofTest 1

输入:

Line #1.
Line #2.
Line #3.

输出:

End-of-file reached at line 4.