Jones
Jones

Reputation: 1214

Runtime error with Crystal - "Error opening file"

So I've got the following code causing issues:

if File.file?(indexPath)
    puts "Have to move index"
    File.rename(indexPath, "#{indexPath}.old")
end
File.new(indexPath)
File.write(indexPath, "test" )#handler.getDoc)
sleep 60.second

I would assume that this would check if the file exists, and back it up before writing a new index.html. Instead, I get the following runtime error:

Error opening file './assets/index.html' with mode 'r': No such file or directory (Errno)
0x10098ab45: *CallStack::unwind:Array(Pointer(Void)) at ??
0x10098aae1: *CallStack#initialize:Array(Pointer(Void)) at ??
0x10098aab8: *CallStack::new:CallStack at ??
0x10097c001: *raise<Errno>:NoReturn at ??
0x1009c9dd9: *File#initialize<String, String, Int32, Nil, Nil>:(Event::Event | Nil) at ??
0x1009cbba9: *File#initialize<String>:(Event::Event | Nil) at ??
0x1009cbb51: *File::new<String>:File at ??
0x10097148b: __crystal_main at ??
0x100981758: main at ??

Upvotes: 0

Views: 448

Answers (1)

Jonne Ha&#223;
Jonne Ha&#223;

Reputation: 4857

File.new creates a new instance of the File class, not a new file. Since you give it no further arguments it tries to open the given file in read mode, you just moved it away so that fails.

To create an empty file one would use File.touch, however opening a file in write mode, which File.write internally does, creates the file when it does not exist.

So just removing the call to File.new should work fine.

Upvotes: 1

Related Questions