来自stdin的Haskell读取文件

SNp*_*Npn 0 stdin haskell readfile

我需要编写一个haskell程序,它从命令行参数中检索文件并逐行读取该文件.我想知道如何处理这个,我是否必须将命令行参数作为字符串并将其解析为openFile或其他什么?我对haskell很新,所以我很失落,任何帮助都会受到赞赏!

huo*_*uon 8

是的,如果想要将文件特定为参数,则必须获取参数并将其发送到openFile.

System.Environment.getArgs将参数作为列表返回.所以给予test_getArgs.hs喜欢

import System.Environment (getArgs)

main = do
        args <- getArgs
        print args
Run Code Online (Sandbox Code Playgroud)

然后,

$ ghc test_getArgs.hs -o test_getArgs
$ ./test_getArgs
[]
$ ./test_getArgs arg1 arg2 "arg with space"
["arg1","arg2","arg with space"]
Run Code Online (Sandbox Code Playgroud)

所以,如果你想读一个文件:

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`
Run Code Online (Sandbox Code Playgroud)

(注意代码没有错误恢复:如果没有参数怎么办,所以args是空的(head会失败)?如果文件不存在/不可读怎么办?)