class File

Overview

A File instance represents a file entry in the local file system and allows using it as an IO.

file = File.new("path/to/file")
content = file.gets_to_end
file.close

# Implicit close with `open` and a block:
content = File.open("path/to/file") do |file|
  file.gets_to_end
end

# Shortcut of the above:
content = File.read("path/to/file")

# Write to a file by opening with a "write mode" specified.
File.open("path/to/file", "w") do |file|
  file.print "hello"
end
# Content of file on disk will now be "hello".

# Shortcut of the above:
File.write("path/to/file", "hello")

See new for various options mode can be.

Temporary Files

Every tempfile is operated as a File, including initializing, reading and writing.

tempfile = File.tempfile("foo")

File.size(tempfile.path)                   # => 6
File.info(tempfile.path).modification_time # => 2015-10-20 13:11:12 UTC
File.exists?(tempfile.path)                # => true
File.read_lines(tempfile.path)             # => ["foobar"]

Files created from tempfile are stored in a directory that handles temporary files (Dir.tempdir):

File.tempfile("foo").path # => "/tmp/foo.ulBCPS"

It is encouraged to delete a tempfile after using it, which ensures they are not left behind in your filesystem until garbage collected.

tempfile = File.tempfile("foo")
tempfile.delete

Included Modules

Defined in:

extensions.cr

Instance Method Summary

Instance Method Detail

def expand_path #

[View source]
def real_path #

[View source]