SNpn
SNpn

Reputation: 2207

Haskell how to read a file specified as a command line argument

I need to write a haskell program that retrieves a file from command line argument and read that file line by line. I was wondering how to approach this, do I have to get the command line argument as a string and parse that into openFile or something? I'm quite new to haskell so I'm pretty lost, any help would be appreciated!

Upvotes: 0

Views: 3725

Answers (2)

huon
huon

Reputation: 102106

Yes, if one wants to specific a file as an argument then one will have to get the arguments and send that to openFile.

System.Environment.getArgs returns the arguments as a list. So given test_getArgs.hs like

import System.Environment (getArgs)

main = do
        args <- getArgs
        print args

Then,

$ ghc test_getArgs.hs -o test_getArgs
$ ./test_getArgs
[]
$ ./test_getArgs arg1 arg2 "arg with space"
["arg1","arg2","arg with space"]

So, if you want to read a single file:

import System.Environment (getArgs)
import System.IO (openFile, ReadMode, hGetContents)

main = do
        args <- getArgs
        file <- openFile (head args) ReadMode
        text <- hGetContents file
        -- do stuff with `text`

(N.B. that code has no error recovery: what to do if there were no arguments and so args was empty (head will fail)? What if the file doesn't exist/isn't readable?)

Upvotes: 8

Frerich Raabe
Frerich Raabe

Reputation: 94349

First, use getArgs to get the command line arguments. I guess the first one is most interesting to you. Then, use the openFile function to open the file. Finally, use hGetLine to read from the opened file line-by-line.

Upvotes: 3

Related Questions