Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell compilation with an input file, error openFile: does not exist (No such file or directory)

Tags:

haskell

I apologize if this is a simple question. I have specified an input file which is in the same directory of the code source file.

isprime :: Int -> [Int] -> Bool 
isprime ...

main = do
  handle <- openFile "primes-to-100k.txt" ReadMode
  contents <- hGetContents handle
  i <- getLine
  print $ isprime (read i::Int) $ map (\x->read x::Int) $ lines contents
  hClose handle

The code runs well when I use "runhaskell Q111.hs" in shell, but when I compile it with "ghc --make Q111.hs and run, I got an error message

Q111: primes-to-100k.txt: openFile: does not exist (No such file or directory) logout

The point is that the code runs well with ghci and runhaskell, but the executable can't find the input txt.

Do I have to provide the input txt to compiler using someway?

like image 224
Larry Avatar asked Feb 13 '14 21:02

Larry


1 Answers

How are you running the executable? The text file would have to be in the directory you run the program from, which may or may not be where the program is. If you are running ./Q111 from the command line, or if you are double-clicking Q111.exe in Windows, then the text file must be in the same folder as the executable. If you are in a different directory on the command line, then the text file would have to be wherever your current directory is, and not the directory where the executable is.

EDIT: Just saw from your other comment that you are on OS X, and (I assume) are double-clicking the program. From what you said I guess that OS X sets the current directory of such-executed programs to be your home. If you want to get the directory of your program, see the answers to this question. If you use the FindBin package they mention:

main = do
  exedir <- getProgPath
  handle <- openFile (exedir ++ "/primes-to-100k.txt") ReadMode
  ...
like image 112
Onyxite Avatar answered Sep 23 '22 10:09

Onyxite