【发布时间】:2016-07-09 16:53:00
【问题描述】:
我想读取一个文件,对其进行处理,然后将结果写入另一个文件;输入文件名将通过控制台参数提供,输出文件名由输入文件名生成。
如果没有提供参数,我希望它透明地“故障转移”到标准输入/标准输出;本质上,如果提供了文件名,我会将 stdin/stdout 重定向到相应的文件名,这样无论是否提供了文件名,我都可以透明地使用 interact。
这里的代码在多余的 else 中与虚拟输出一起被破解。什么是正确的、惯用的做法?
这可能与 Control.Monad 的 when 或 guard 有关,正如在类似问题中指出的那样,但也许有人已经写过了。
import System.IO
import Data.Char(toUpper)
import System.Environment
import GHC.IO.Handle
main :: IO ()
main = do
args <- getArgs
if(not $ null args) then
do
print $ "working with "++ (head args)
finHandle <- openFile (head args) ReadMode --open the supplied input file
hDuplicateTo finHandle stdin --bind stdin to finName's handle
foutHandle <- openFile ((head args) ++ ".out") WriteMode --open the output file for writing
hDuplicateTo foutHandle stdout --bind stdout to the outgoing file
else print "working through stdin/redirect" --get to know
interact ((++) "Here you go---\n" . map toUpper)
【问题讨论】:
标签: haskell io monads io-redirection