Haskell从文件句柄读取
示例
像在I/O库的其他几个部分中一样,隐式使用标准流的函数在System.IO执行相同工作时具有对等的功能,但是左侧有一个额外的参数,类型为Handle,表示正在处理的流。例如,getLine::IOString有一个对应项hGetLine::Handle->IOString。
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 "输入文件名: "
filename <- getLine
handle <- openFile filename ReadMode
dumpFile handle filename 1
hClose handle文件内容example.txt:
This is an example. Hello, world! This is another example.
输入:
输入文件名: example.txt
输出:
example.txt:1: This is an example. example.txt:2: Hello, world! example.txt:3: This is another example
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短