Hatena::ブログ(Diary)

kazuhoのメモ置き場

2010-04-24

ファイルを追記モードで開くとseekできない、という話 (C言語の高水準I/OとかPerlとか)

C言語に初めて触ってから20年のロートルですが今まで知りませんでした。man fopen より。

The fopen() function opens the file whose name is the string pointed to by filename and associates a
stream with it.

``a''   Open for writing.  The file is created if it does not exist.  The stream is positioned at the
        end of the file.  Subsequent writes to the file will always end up at the then current end of
        file, irrespective of any intervening fseek(3) or similar.

``a+''  Open for reading and writing.  The file is created if it does not exist.  The stream is posi-
        tioned at the end of the file.  Subsequent writes to the file will always end up at the then
        current end of file, irrespective of any intervening fseek(3) or similar.

いやらしいのが、fseek は成功を返すのに、データを書く位置は必ずファイルの末尾になる、と。なんでそんな仕様になってるんだろう? Perl の標準関数 open (の >> モード) も同様。

やっぱり低水準I/Oが好き♡と思った土曜の夜でしたorz

kosakikosaki 2010/04/25 01:24 歴史的理由だったと記憶しています。Unix黎明期はO_APPENDがなかったのでライブラリでファイル末尾にlseekしてからwriteしていたのでレースがあった。んで、O_APPENDで解決したのだけれど、明示的な末尾lseekをエラーにするのは互換性の問題があって云々・・・とかいうストーリーだった気がする。詳細忘れたのでウソかもしれません

kazuhookukazuhooku 2010/04/25 01:44 なるほどです。ありがとうございます。

スパム対策のためのダミーです。もし見えても何も入力しないでください
ゲスト


画像認証

トラックバック - http://d.hatena.ne.jp/kazuhooku/20100424/1272125367