Haskell IO and closing files

后端 未结 6 1985
走了就别回头了
走了就别回头了 2021-01-30 21:21

When I open a file for reading in Haskell, I\'ve found that I can\'t use the contents of the file after closing it. For example, this program will print the contents of a file:<

6条回答
  •  心在旅途
    2021-01-30 21:50

    As previously noted, hGetContents is lazy. readFile is strict, and closes the file when it's done:

    main = do contents <- readFile "foo"
              putStr contents
    

    yields the following in Hugs

    > main
    blahblahblah
    

    where foo is

    blahblahblah
    

    Interestingly, seq will only guarantee that some portion of the input is read, not all of it:

    main = do inFile <- openFile "foo" ReadMode
              contents <- hGetContents $! inFile
              contents `seq` hClose inFile
              putStr contents
    

    yields

    > main
    b
    

    A good resource is: Making Haskell programs faster and smaller: hGetContents, hClose, readFile

提交回复
热议问题