Forum: Ruby Creating Files

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Andy Ferra (Guest)
on 2006-02-24 04:55
(Received via mailing list)
Could someone please tell me how to create a new file?

Thank you.
E. Saynatkari (Guest)
on 2006-02-24 05:24
Andy Ferra wrote:
> Could someone please tell me how to create a new file?

You could use FileUtils.touch or just File.open a filename
in write-mode. You can take a look at the documentation for
those classes by typing

  ri FileUtils
  ri File

On your command-line.

> Thank you.


E
Tony M. (Guest)
on 2006-02-24 07:00
(Received via mailing list)
Hi,

For an empty file, I guess the easiest way would be:

# Create a new file and write on it
#
begin
         f=File::open("test.txt","w")
rescue SystemCallError
         puts "Problem with File::open #1"
         #... something went wrong...
else
         f.close
end


# The file will be closed afterwards
#
begin
         File::open("/etc/test.txt","w") do | f |
                 # Do somethinf with "f" ...
         end
rescue SystemCallError
         # The file can't be created
         puts "Problem with File::open #2"
end


# If all you want is create an empty file...
#
begin
         File::open("test.txt","w") {}
rescue SystemCallError
         # The file can't be created
         puts "Problem with File::open #3"
end

read "ri IO::open" for more info!

Merc.
This topic is locked and can not be replied to.