How to read from a file in Haskell
We can read contents from a file in Haskell in several ways. In this Answer, we'll try two different methods to read from a file in Haskell.
Using the readFile function
We can read the contents of a file in Haskell using the readFile function as shown below:
main :: IO ()main = docontents <- readFile "educative.txt"putStrLn contents
Explanation
Line 1: We declare the
mainfunction with typeIO().Line 2: The
mainfunction begins here.Line 3: We read the file
educative.txtand bind its contents to the variablecontents.Line 4: We display the contents of the file on the console.
Using openFile and hGetContents
Another method to read files in Haskell is using the openFile and hGetContents functions together. Here is an example of how this can be done:
import System.IOmain :: IO ()main = dofileHandle <- openFile "educative.txt" ReadModecontents <- hGetContents fileHandleputStrLn contentshClose fileHandle
Explanation
Line 1: We import the
System.IOmodule.Line 3: We declare the
mainfunction with typeIO().Line 4: The
mainfunction begins here.Line 5: We open the file
educative.txtfile inReadModeand bind the resulting file handle to thefileHandlevariable.Line 6: We read the contents of the file
educative.txtby passingfileHandleas an argument to thehGetContentsfunction, and bind those contents to the variablecontents.Line 7: We display the contents of the file on the console.
Line 8: We close the file handle to ensure that the file is properly closed once its contents have been read.
Free Resources