开发者

How to change the mode from read-write to read-only in a File-resource object in Ruby?

My code needs to create a file, write to it, and then change the file-bject to read-only mode.

What I do now, seems kindof ugly: I open the file with mode "wb", write to it, close it, then re-open it with mode "rb":

open(@cached_file_name, 'wb') { |file| file.write("foo") }    
@cached_file = open(@cached_file_name, 'rb')

Is it possible to change the file from "wb" to "rb开发者_运维技巧" without opening and closing it? Like:

@cached_file = open(@cached_file_name, 'wb')
@cached_file.write("foo")
@cached_file.mode= 'r'

I am not aware of such a mode= method though.


No, I'm not aware of a way to do that, and I think that stems from the open syscall in Linux which can't do that.

The RubyDoc for IO.new states:

When the mode of original IO is read only, the mode cannot be changed to be writable. Similarly, the mode cannot be changed from write only to readable. If such a wrong change is directed, timing where the error actually occurs is different according to the platform.

But I note that that doesn't explicity state what you can or can't do for read/write modes...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜