Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby Temporary files inside temporary directory

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.

like image 760
user2534381 Avatar asked Nov 23 '22 18:11

user2534381


1 Answers

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
like image 71
jane mason Avatar answered Dec 15 '22 21:12

jane mason