從檔案控制代碼中讀取

與 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