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.hs
educative.txt
main :: IO ()
main = do
contents <- readFile "educative.txt"
putStrLn contents

Explanation

  • Line 1: We declare the main function with type IO().

  • Line 2: The main function begins here.

  • Line 3: We read the file educative.txt and bind its contents to the variable contents.

  • 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:

main.hs
educative.txt
import System.IO
main :: IO ()
main = do
fileHandle <- openFile "educative.txt" ReadMode
contents <- hGetContents fileHandle
putStrLn contents
hClose fileHandle

Explanation

  • Line 1: We import the System.IO module.

  • Line 3: We declare the main function with type IO().

  • Line 4: The main function begins here.

  • Line 5: We open the file educative.txt file in ReadMode and bind the resulting file handle to the fileHandle variable.

  • Line 6: We read the contents of the file educative.txt by passing fileHandle as an argument to the hGetContents function, and bind those contents to the variable contents.

  • 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

Copyright ©2025 Educative, Inc. All rights reserved