2015-10-30 10 views
8

私は、ファイルがutf-8 characteresを持っていない限り、正常に動作し、次のコードがあります。 hGetContents: invalid argument (invalid byte sequence)読むファイル

:UTF-8 characteresで

module Main where 
import Ref 
main = do 
    text <- getLine 
    theInput <- readFile text 
    writeFile ("a"++text) (unlist . proc . lines $ theInput) 

を、私はこれを取得

私が扱っているファイルはUTF-8文字ですので、可能ならばRefからインポートされた関数を再利用するためにこの例外を処理したいと思います。

UTF-8ファイルをIO Stringと読んで、Refの機能を再利用する方法はありますか。私のコードにどのような変更を加える必要がありますか?前もって感謝します。

は、私は私のRefモジュールからの関数の宣言を添付:

unlist :: [String] -> String 
proc :: [String] -> [String] 

プレリュードから:

lines :: String -> [String] 

答えて

2

おかげで、私自分で解決策を見つけました。 は実際に私が働いていたファイルは、この成文化を持っています

ISO-8859 text, with CR line terminators 

だから私のHaskellコードでそのファイルを操作することではなく、この成文化を持っている必要があります。

UTF-8 Unicode text, with CR line terminators 

をあなたはしてファイルの体系化を確認することができますこのようなユーティリティfile

$ file filename 

がこのからの指示に従ったファイル成文化を変更するには!

0

使用System.IO.Encoding

ユニコードサポートの欠如は、標準のHaskell IOライブラリのよく知られた問題です。

module Main where 

import Prelude hiding (readFile, getLine, writeFile) 
import System.IO.Encoding 
import Data.Encoding.UTF8 

main = do 
    let ?enc = UTF8 
    text <- getLine 
    theInput <- readFile text 
    writeFile ("a"++text) (unlist . proc . lines $ theInput) 
3

これは、あなたがより多くの機能を使用する必要がありますが、ちょうどGHCの基本的な(しかし、標準から拡張)System.IOモジュールを行うことができます答えを

module Main where 

import Ref 
import System.IO 

main = do 
    text <- getLine 
    inputHandle <- openFile text ReadMode 
    hSetEncoding inputHandle utf8 
    theInput <- hGetContents inputHandle 
    outputHandle <- openFile ("a"++text) WriteMode 
    hSetEncoding outputHandle utf8 
    hPutStr outputHandle (unlist . proc . lines $ theInput) 
    hClose outputHandle -- I guess this one is optional in this case.