mateuszjp
mateuszjp

Reputation: 11

Haskell - save unicode (String, characters) to file

environment: windows 7 64, ghci 7.8.3

IN GHCI

\197 <-> Ć

Prelude> putStrLn "\197"
*** Exception: <stdout>: hPutChar: invalid argument (invalid character)

Finally

I try use writeFile function to save String to file;

writeFile "filename.txt" "ćĆ"
-- content in "filename.txt" -> †Ź

how to write to character quotation mark (")

content2 = "\"http:\\www.google.com\""
writeFile "filename2.txt content2

If this is wrong way, how to download webpage (html) and save it on hdd and then open it in web browser,

Upvotes: 1

Views: 922

Answers (1)

Jedai
Jedai

Reputation: 1477

By default, a newly created handle is affected the locale encoding the OS reported (see System.IO.localeEncoding). In Windows that may be a very old codepage... So one way is to change the codepage to 65001 (with chcp 65001) prior to launching the Haskell executable. If that is unsatisfactory, you can change the encoding of any Handle in your code with System.IO.hSetEncoding (even stdout) or even use ByteString IO (binary) and do the encoding/decoding yourself (probably overkill if you don't need very precise control over it). Note that this means that writeFile can't be used since you don't see the handle, you'll have to write your own variant :

writeFileWithEncoding fp content enc =
  withFile fp WriteMode $ \h -> do
    hSetEncoding h enc
    hPutStr h content

Or just a version specialized for utf8.

Upvotes: 1

Related Questions