Forum: Ruby How to create a file

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.
Zhao Y. (Guest)
on 2009-01-13 09:10
I use this code to write to a file: File.new(@FILE_NAME,"w"). If the
file name doesn't exist, I will get "No such file" error. How can I
create the file if it doesn't exist?

thanks.
Robert K. (Guest)
on 2009-01-13 09:20
(Received via mailing list)
On 13.01.2009 08:09, Zhao Yi wrote:
> I use this code to write to a file: File.new(@FILE_NAME,"w"). If the
> file name doesn't exist, I will get "No such file" error. How can I
> create the file if it doesn't exist?

I cannot reproduce this behavior.  Did you make sure that the directory
exists where you want to create your file?  In case not you probably
want to have a look at FileUtils.mkdir_p:

http://ruby-doc.org/stdlib/libdoc/fileutils/rdoc/c...

Cheers

  robert
Dave B. (Guest)
on 2009-01-15 13:17
It could be that the operating system is unable to create a file with
that file name. For instance on Windows:

C:\>irb
irb(main):001:0> @FILE_NAME = "."
=> "."
irb(main):002:0> File.new(@FILE_NAME, "w")
Errno::EACCES: Permission denied - .
        from (irb):2:in `initialize'
        from (irb):2:in `new'
        from (irb):2

This could be a particular problem when using international character
sets.

Dave
Zhao Y. (Guest)
on 2009-01-16 02:42
Robert K. wrote:
> On 13.01.2009 08:09, Zhao Yi wrote:
>> I use this code to write to a file: File.new(@FILE_NAME,"w"). If the
>> file name doesn't exist, I will get "No such file" error. How can I
>> create the file if it doesn't exist?
>
> I cannot reproduce this behavior.  Did you make sure that the directory
> exists where you want to create your file?  In case not you probably
> want to have a look at FileUtils.mkdir_p:
>
> http://ruby-doc.org/stdlib/libdoc/fileutils/rdoc/c...
>
> Cheers
>
>   robert

The directory doesn't exist, that's the problem.

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