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
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短