Library contents

Ruby File.open with EXCL

Create a new file only if its name is still available.

A simple example

File.open with EXCL

  1. Start with An unused name a.txt
  2. Do this Create exclusively twice
  3. Result First succeeds, second fails
The second attempt encounters the file created by the first.

Syntax

Ruby syntax
File.open(name, exclusive_flags)
Run these examples in Ruby

Save one example at a time as lesson.rb. Use Ruby 2.6 or later.

ruby lesson.rb

Stop two desks claiming the same ticket

Two desks request the same claim number. Use exclusive creation for the second reservation so it cannot replace the first ticket, then report the collision to the clerk.

Resultalready issued
lesson.rb
require 'tmpdir'

Dir.mktmpdir do |folder|
  Dir.chdir(folder) do
    flags = File::WRONLY | File::CREAT | File::EXCL
    File.open("claim", flags) { |f| f.write("issued") }
    begin
      File.open("claim", flags) { }
    rescue Errno::EEXIST
      puts "already issued"
    end
  end
end
Output
already issued

The second reservation identifies the existing name without overwriting its contents.

Advertisements

Prepare a gallery label

A curator stores a short UTF-8 caption beside an exhibit. Two desks try to reserve the same filename using exclusive creation. What happens to the first successful reservation when the second desk tries?

GivenFile contents “clay”
Worked resultOriginal kept

Prepare a studio handover

A stage manager saves a two-word instruction for the next shift. Two desks try to reserve the same filename using exclusive creation. What happens to the first successful reservation when the second desk tries?

GivenFile contents “ring bell”
Worked resultOriginal kept

What to watch for

Checking for existence before creation opens a race. Use an atomic create-if-absent operation.

Documentation for File.open with EXCL