基礎プログラミング I 第 9 回 (Ruby であそぼ / 広告ページの作成) 「参加してくれた人は誰?」 講義ノート目次

ファイルを共通な directory /tmp にしまっておき、 誰でも書き込めるようにしてみよう。adv_logfile.


#!/usr/koeki/bin/ruby

if FileTest.exist?("/tmp/message.dat") 
FileTest.writable?("/tmp/message.dat") ファイルがかき込みできるなら true print("一言メッセージを書き込んでね: \n") message = gets.chomp open("/tmp/message.dat", "a") do |msg|
msg.printf("%s: %s\n", `whoami`.chomp, message)
end printf("ファイルに書きこんだよ\n") printf("メッセージを見るには cat /tmp/message.dat してね\n")
else printf("ファイルを作ったよ\n")
system("touch /tmp/message.dat") system("ls -l /tmp/message.dat") File.chmod(0100666, "/tmp/message.dat") ファイルを chmod +w する system("ls -l /tmp/message.dat") print("一言メッセージを書き込んでね: \n") message = gets.chomp open("/tmp/message.dat", "w") do |msg|
msg.printf("%s: %s\n", `whoami`.chomp, message)
end
end

whoami コマンドは使用しているユーザ名を知るためのコマンドである。

ファイルの取り扱い

FileFileTest は、ファイルの存在および状態について知ることができる method である。

system は、コマンドを実行するときに使用する。 使わせるファイルは、 chmod g+w するのを忘れないこと。