How do open a file for writing only if it doesn't already exist in ruby

匿名 (未验证) 提交于 2019-12-03 02:56:01

问题:

I want to open a file for writing but only if it doesn't already exist. If the file exists I want to raise an exception. Is this the best way to do it?

filename = 'foo' raise if File.exists? filename File.open(filename, 'w') do |file|    file.write contents end

What is the most idiomatic way to do this without the race condition?

回答1:

After doing some further research, it seems you can use the File::CREAT and File::EXCL mode flags.

filename = 'foo' File.open(filename, File::WRONLY|File::CREAT|File::EXCL) do |file|   file.write contents end

In this case, open will raise an exception if the file exists. After running once, this program succeeds without error, creating a file named foo. On the second run, the program emits this:

foo.rb:2:in `initialize': File exists - foo (Errno::EEXIST)     from foo.rb:2:in `open'     from foo.rb:2

From man open:

       O_WRONLY        open for writing only        O_CREAT         create file if it does not exist        O_EXCL          error if O_CREAT and the file exists


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!