ファイルを1行ずつ読み込む
メモリを効率よく使うには処理する分ずつ読み込んだ方がよいのと、ファイル全体を読み込んでも処理の対象になる部分を切り出したりするのが面倒になってしまうので、一行ずつ読み込んで処理する事が多いと思います。ここでは1行ずつ読み込んで、ダイアログに表示するスクリプトのサンプルです。
AppleScript
1行ずつ読み込む部分では、repeat文を使っています。ファイルの行数を数えて、カウンタiを使ってその回数分repeatする事もできますが、ここではファイルの最後までくると、EOFエラーが起こるのを利用して、「try on 〜 error 〜 end try」でrepeatから出る方法を使っています。こうしておけば、行数を数えて繰り返し回数を指定する手間が省けます。
try –ファイルを開く
open for access inFile without write permission –読み込むファイルを開く
on error
display alert “ファイルを開く際にエラー発生”
try
close access inFile
end try
end tryrepeat
try
read inFile before return –1行を読み込み
set aData to result
display dialog aData
on error number errNum
if errNum = -39 then –End of file error
exit repeat
else
error number errNum
end if
end try
end repeattry –ファイルを閉じる
close access inFile
on error
display alert “エラー発生”
try
close access inFile
end try
end try
read文でbefore returnとすれば、行末の改行を含めずに、until returnとすれば行末の改行を含めて読み込む事ができます。
エラー番号の一覧(リファレンス)はdevelper.apple.comにあります。今回のエラー番号はこの中のOperating System Errorsに規定されています。
http://developer.apple.com/documentation/AppleScript/