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.
readFile
functionWe 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
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.
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
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