3307.hs 1.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
import Control.Exception

import System.Directory
import System.Environment
import System.IO

import Data.Char
import Data.List

import GHC.IO.Encoding

main = do
Ian Lynagh's avatar
Ian Lynagh committed
13
14
    hSetBuffering stdout NoBuffering

15
    -- 1) A file name arriving via an argument
Ian Lynagh's avatar
Ian Lynagh committed
16
    putStrLn "Test 1"
17
    [file] <- getArgs
Ian Lynagh's avatar
Ian Lynagh committed
18
    print $ map ord file
19
    readFile file >>= putStr
Ian Lynagh's avatar
Ian Lynagh committed
20

21
    -- 2) A file name arriving via getDirectoryContents
Ian Lynagh's avatar
Ian Lynagh committed
22
    putStrLn "Test 2"
23
    [file] <- fmap (filter ("chinese-file-" `isPrefixOf`)) $ getDirectoryContents "."
Ian Lynagh's avatar
Ian Lynagh committed
24
    print $ map ord file
25
    readFile file >>= putStr
Ian Lynagh's avatar
Ian Lynagh committed
26

27
    -- 3) A file name occurring literally in the program
batterseapower's avatar
batterseapower committed
28
29
    -- The file is created with a UTF-8 file name as well, so this will only work in Windows or a
    -- UTF-8 locale, or this string will be encoded in some non-UTF-8 way and won't match.
Ian Lynagh's avatar
Ian Lynagh committed
30
    putStrLn "Test 3"
Ian Lynagh's avatar
Ian Lynagh committed
31
32
33
    let file = "chinese-file-小说"
    print $ map ord file
    readFile file >>= putStr
Ian Lynagh's avatar
Ian Lynagh committed
34

35
    -- 4) A file name arriving via another file.
batterseapower's avatar
batterseapower committed
36
37
38
    -- Again, the file is created with UTF-8 contents, so we read it in that encoding.
    -- Once again, on non-Windows this may fail in a non-UTF-8 locale because we could encode the valid
    -- filename string into a useless non-UTF-8 byte sequence.
Ian Lynagh's avatar
Ian Lynagh committed
39
    putStrLn "Test 4"
batterseapower's avatar
batterseapower committed
40
    str <- readFileAs utf8 "chinese-name"
Ian Lynagh's avatar
Ian Lynagh committed
41
42
43
    let file = dropTrailingSpace str
    print $ map ord file
    readFile file >>= putStr
44
45
46
47
48
49
50
51
52

readFileAs :: TextEncoding -> FilePath -> IO String
readFileAs enc fp = do
    h <- openFile fp ReadMode
    hSetEncoding h enc
    hGetContents h

dropTrailingSpace :: String -> String
dropTrailingSpace = reverse . dropWhile (not . isAlphaNum) . reverse