2011-06-10 50 views
3

所以我試圖做一個程序,它從一個句柄讀取和寫入到stdout,就像這樣:貓模擬器

import IO 
import System 

cat w = do 
      fromHandle <- getAndOpenFile w ReadMode 
      contents <- hGetContents fromHandle 
      putStr contents 
      putStr "Done." 

getAndOpenFile :: String -> IOMode -> IO Handle 

getAndOpenFile name mode = 
     do 
     catch (openFile name mode) 
     (\_ -> do 
       putStrLn ("Cannot open "++ name ++"\n") 
       return()) 

我是相當新的HS和它看起來這應該是比我爲自己做的更簡單。任何幫助我進一步移動的建議?

用法將是./cat「foo.txt」,並將foo.txt文件中的文本打印到stdOut。

+3

最好的問題標題。 ·ω· – deceze 2011-06-10 06:16:29

+0

簡潔,雙關。 – 2011-06-10 06:20:25

+0

http://donsbot.wordpress.com/2006/12/18/programming-haskell-argument-handling-and-a-complete-cat/ – 2011-06-10 10:43:57

回答

4

有下面的功能,它做你想做的。

readFile :: FilePath -> IO String 

使用這種與putStr永遠打印IO字符串

+0

這個工作,但只在GHCI。如果我試圖用ghc來編譯它--make cat.hs,我得到一個錯誤「函數'main'沒有在模塊'Main'中定義。」 – 2011-06-10 06:38:27

+0

編譯代碼時需要main函數。你粘貼的代碼沒有實際執行cat函數的主函數。同樣在主函數中,您需要從參數中獲取文件名到程序,因爲cat會將文件名作爲參數 – Ankur 2011-06-10 06:40:43

+0

大大的幫助,非常感謝:) – 2011-06-10 06:48:57