1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

readfile()でファイルを読み込んでからiconv()で文字エンコーディングを変換する

Posted at

環境Debian 8.5/Vim 7.4.1902

readfile()でファイルを読み込んでも自動的に文字エンコーディングの変換をしてくれません。
iconv()も自動的に文字エンコーディングを判断して変換してくれないので、事前に文字エンコーディングを調べる必要があります。

サンプルでは文字エンコーディングcp932で保存したファイルcp932.txtを読み込ませます。

cp932.txt

Vim起動

vim -Nu NONE -S sample.vim

サンプルスクリプト

sample.vim
let filename = 'cp932.txt'
let f = readfile(filename)
echo f

結果

['<82><a0>']

リストに含まれる値がバイナリで表示されてしまいました。
**['あ']が表示されません。
どうにかして
['あ']**を表示させたいので方法を調べました。

バッファにファイルを開いて文字エンコーディングを取得してから変換する

fileencodingsを設定する必要があります。
cp932.txtを新規バッファに開くと、&fileencodingで文字エンコーディングが取得できます。

tabeditを実行した時に自動コマンドが発動しないように、noautocmdを使って一時的に自動コマンドを無効にしています。

Vim起動

vim -Nu NONE -S sample1.vim

サンプルスクリプト

sample1.vim
set fileencodings=ucs-bom,utf-8,euc-jp,sjis,cp932,default,latin1
let filename = 'cp932.txt'
execute 'noautocmd tabedit ' . filename
let enc = &fileencoding
bwipeout
let f = readfile(filename)
call map(f, 'iconv(v:val, enc, &encoding)')
echo f

結果

['あ']

文字エンコーディングが変換されて**['あ']**と表示されました。

外部プログラムで文字エンコーディングを取得してから変換する

外部プログラムでファイルの文字エンコーディングを調べてから変換する方法です。
サンプルではPHPを使って文字エンコーディングを取得しています。
このサンプルを動かすにはPHPが利用できる環境が必要です。

Vim起動

vim -Nu NONE -S sample2.vim

サンプルスクリプト

sample2.vim
let filename = 'cp932.txt'
let phpcmd = "php -r " .
            \ "\"mb_detect_order('UTF-8,eucJP-win,SJIS-win');" .
            \ "echo mb_detect_encoding(" .
            \ "file_get_contents('" . filename . "'));\""
let enc = system(phpcmd)
let f = readfile(filename)
call map(f, 'iconv(v:val, enc, &encoding)')
echo f

文字エンコーディングが変換されて**['あ']**と表示されました。

その他

iconv()の第二引数に渡せる文字エンコーディング名については、Linuxではターミナルでiconv -lを実行すると確認できます。

今回は試してませんが拡張インターフェース(if_pyth、if_rubyなど)を使って文字エンコーディングを取得することも出来ると思います。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?