Reputation: 225
I want to create temporary files inside temporary directory. below is my code for this.
require 'tmpdir'
require 'tempfile'
Dir.mktmpdir do |dir|
Dir.chdir(dir)
TemFile.new("f")
sleep 20
end
It gives me this exception:
Errno::EACCES: Permission denied - C:/Users/SANJAY~1/AppData/Local/Temp/d20130724-5600-ka2ame
, because ruby is trying to delete a temp directory, which is not empty.
Please help me to create a temp file inside temp directory.
Upvotes: 6
Views: 8061
Reputation: 41
Hi I created the temporary directory with the prefix "foo" and the tempfile with the prefix cats
dir = Dir.mktmpdir('foo')
begin
puts('Directory path:'+ dir) #Here im printing the path of the temporary directory
# Creating the tempfile and giving as parameters the prefix 'cats' and
# the second parameter is the tempdirectory
tempfile = Tempfile.new('cats', [tmpdir = dir])
puts('File path:'+ tempfile.path) #Here im printing the path of the tempfile
tempfile.write("hello world")
tempfile.rewind
tempfile.read # => "hello world"
tempfile.close
tempfile.unlink
ensure
# remove the directory.
FileUtils.remove_entry dir
end
And since we print the paths on console we can get the following
Directory path: /tmp/foo20181116-9699-1o7jc6x
File path: /tmp/foo20181116-9699-1o7jc6x/cats20181116-9699-7ofv1c
Upvotes: 2
Reputation: 2311
You should use the Tempfile class.
require 'tempfile'
file = Tempfile.new('foo')
file.path # => A unique filename in the OS's temp directory,
# e.g.: "/tmp/foo.24722.0"
# This filename contains 'foo' in its basename.
file.write("hello world")
file.rewind
file.read # => "hello world"
file.close
file.unlink # deletes the temp file
To create temporary folders, you can use Dir.mktmpdir.
Upvotes: -1