人気ブログランキング | 話題のタグを見る

System.IO モジュール(17) Binary input and output

System.IO モジュールの Binary input and output セクションの関数は、バイナリーファイルの読み書きをする関数だ。バイナリーファイルの読み書きなどやったことがないので、このセクションはとばそうかと思ったが、読み込みの実験だけはやってみた。

withBinaryFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r 関数の使い方は、withFile 関数と同じだが、バイナリーモードでファイルをオープンする。

Prelude System.IO> withBinaryFile "hello.txt" ReadMode (\hdl -> hGetContents hdl >>= print)
"hello, world\r\nhow are you?\r\n"

次の withFile の実行例と比べると、改行文字の自動変換はせずに、忠実にコードを読み出していたのが分かる。

Prelude System.IO> withFile "hello.txt" ReadMode (\hdl -> hGetContents hdl >>= print)
"hello, world\nhow are you?\n"

これだけでは本当にバイナリーファイルを読み出しているのか不安なので、本物のバイナリーファイルを試してみたがどうやらちゃんと読み出しているようだ。

Prelude System.IO> withBinaryFile "hello.o" ReadMode (\hdl -> hGetContents hdl >>= print)
"L\SOH\ENQ\NUL\NUL\NUL\NUL\NUL\DLE\EOT\NUL\NUL%\NUL\NUL\NUL\NUL\NUL\EOT\SOH.text (以下略)

openBinaryFile :: FilePath -> IOMode -> IO Handle 関数の使い方も、openFile 関数と同じだ。

Prelude System.IO> openBinaryFile "hello.txt" ReadMode >>= (\hdl -> hGetContents hdl >>= print >> hClose hdl)
"hello, world\r\nhow are you?\r\n"

hSetBinaryMode :: Handle -> Bool -> IO () 関数はファイルハンドルのモードをバイナリーモード(True)にしたり、テキストモード(False)にしたり切り替えることができる。

Prelude System.IO> withBinaryFile "hello.txt" ReadMode (\hdl -> hSetBinaryMode hdl False >> hGetContents hdl >>= print)
"hello, world\nhow are you?\n"

上の例では、ファイルをバイナリーモードでオープンしたものの、hSetBinaryMode でファイルハンドルをテキストモードにしているので、ファイルの読み出しがテキストモードになっている。

Binary input and output セクションには他に次のような関数があるが、バイナリーファイルの書き込みの基本的なことを知らないので、残念ながら、スキップする。

hPutBuf :: Handle -> Ptr a -> Int -> IO ()
hGetBuf :: Handle -> Ptr a -> Int -> IO Int
hGetBufSome :: Handle -> Ptr a -> Int -> IO Int
hPutBufNonBlocking :: Handle -> Ptr a -> Int -> IO Int
hGetBufNonBlocking :: Handle -> Ptr a -> Int -> IO Int
by tnomura9 | 2011-09-22 18:32 | Haskell | Comments(0)
<< System.IO モジュール... System.IO モジュール... >>