6

I'm using ghci 6.10.4 at the dos command line in XP, and also in emacs using haskell-mode-2.4

When running programs that operate on stdin, is there a way I can redirect a file to be stdin? For example if I have a function called main that reads from stdin, I can't do:

*Main> main < words.txt

Is there another way?

Also I would like to be able to type stdin into the ghci window, which seems to work, but what is the EOF key? I thought it was Ctrl-D but that doesn't work.

2
  • 3
    I believe in dos/windows Ctrl-Z is the EOF key... Nov 14, 2009 at 20:25
  • Ah yeah. I tried that and thought it failed, but does in fact work, but then as the answer below states, it also closes stdin and you get an error message like : *Main> <stdin>: hLookAhead: invalid argument (Bad file descriptor)
    – justinhj
    Nov 14, 2009 at 22:54

2 Answers 2

6

This will be easier if you rework your main to open the file itself.

import System.Environment
import System.IO

main :: IO ()
main = do
    args <- getArgs
    case args of
      [] -> doStuff stdin
      file:_ ->
        withFile file ReadMode doStuff

doStuff :: Handle -> IO ()
doStuff = …
*Main> System.Environment.withArgs ["main.txt"] main

Don't give a EOF on stdin while within GHCi. If you do, all further attempts to read from stdin will fail:

Prelude> getLine
*** Exception: <stdin>: hGetLine: illegal operation (handle is closed)
Prelude> getContents
*** Exception: <stdin>: hGetContents: illegal operation (handle is closed)
1
  • On Cygwin, CTRL+C seems to cancel an operation while also closing the file handle? How do you cancel the operation without closing the handle? Jun 5, 2015 at 17:37
4

You CAN type :main in GHCi to invoke command line parameters. I'm afraid you'll probably just want to use that.

3
  • 1
    +1 Whoa, when'd they add that? That's definitely shorter than …withArgs…
    – ephemient
    Nov 14, 2009 at 22:02
  • 5
    That's handy but you can't redirect stdin like this: :main < words.txt
    – justinhj
    Nov 14, 2009 at 22:59
  • 1
    Sorry ephemient, but I haven't been using haskell long so it's been here as long as I can remember. And justinhj, why not try this? main = do { args <- getArgs; let file = head args; contents <- readFile file; hPutStr stdin contents; ... } Then you can do :main words.txt
    – codebliss
    Nov 14, 2009 at 23:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.