0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

なぜファイル操作で「読み取り」や「書き込み」を指定する必要があるのか?

Posted at

はじめに

ファイル操作を初めてするとき、誰しもこう思うはずです。

なんでファイルを開くときに "r"(読み取り)とか "w"(書き込み)とか指定する必要があるの?

例えば、こんなコード。

$fp = fopen("data.txt", "r");
fwrite($fp, "Hello!");

このとき、エラーになります。

なぜなら "r"読み取り専用だからです。


なぜ指定が必要なのか?

実は、OSとの関係がある。

ファイルというのは、複数のプログラムが同時に使う可能性があるリソース。

例えば、誰かが書き込み中に、別の人が同時に読み書きしようとしたら、データが壊れたり、競合が起こる可能性がある。

それを防ぐために、「このファイルをどう使うか?」を最初にOSに伝える必要がある。

そうすることで、OSが裏でファイル操作が正常にできるように仕事してくれる。

fopen()のモード指定は、そのための「宣言」ということ。


おわりに

CSの知識って、こういう「ちょっとした違和感」や「なんで?」を解消するのに本当に役立ちます。

もちろん、理解しなくても仕事はできます。

でも、裏側の仕組みがわかると、プログラミングがもっと楽しくなる。

僕は、そう感じています。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?