Haskell readFile非法Char

Jus*_*tin 1 io locale haskell file

我需要读一个包含'ç'ou'á'等字符的文件...问题是当我尝试读取文件时,GHC返回:非法字节序列.有没有解决的办法?

main = do putStr "Insert file path\n"
          a <- getLine
          x <- readFile a
          print x

Main> main
Main> Insert file path
Main> /Users/$HOME/Desktop/File.txt
Main> (illegal byte sequence)
Run Code Online (Sandbox Code Playgroud)

谢谢

eph*_*ent 9

Data.ByteString.readFile将文件作为原始字节流读取,而System.IO.readFile用于localeEncoding解码字符,如果无法使用当前语言环境解码文件内容,则会抛出异常.

如果您想继续使用String而不是ByteString+ decode,并且您知道文件的编码,则可以使用它进行指定

do handle <- openFile a ReadMode
   hSetEncoding handle latin1  -- or whatever applies
   x <- hGetContents handle
Run Code Online (Sandbox Code Playgroud)