从文件句柄中读取

与 I / O 库的其他几个部分一样,隐式使用标准流的函数在 System.IO 中具有执行相同作业的对应项,但在左侧有一个类型为 Handle 的额外参数,表示正在处理的流。例如,getLine::IO String 有一个对应的 hGetLine::Handle -> IO String

import System.IO( Handle, FilePath, IOMode( ReadMode ), 
                  openFile, hGetLine, hPutStr, hClose, hIsEOF, stderr )

import Control.Monad( when )

dumpFile::Handle -> FilePath -> Integer -> IO ()

dumpFile handle filename lineNumber = do      -- show file contents line by line
    end <- hIsEOF handle
    when ( not end ) $ do
        line <- hGetLine handle
        putStrLn $ filename ++ ":" ++ show lineNumber ++ ": " ++ line
        dumpFile handle filename $ lineNumber + 1

main::IO ()

main = do
    hPutStr stderr "Type a filename: "
    filename <- getLine
    handle <- openFile filename ReadMode
    dumpFile handle filename 1
    hClose handle

文件内容 example.txt

This is an example.
Hello, world!
This is another example.

输入:

Type a filename: example.txt

输出:

example.txt:1: This is an example.
example.txt:2: Hello, world!
example.txt:3: This is another example