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`
content = File.open("path/to/file") do |file|
  file.gets_to_end
end

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

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:

file.cr

Class Method Summary

Class methods inherited from module Crystal::System::File

chown(path : String, uid : Int, gid : Int, follow_symlinks : Bool) chown, chown?(path : String, uid : Int, gid : Int, follow_symlinks : Bool) : Bool chown?

Class Method Detail

def self.chown(path : String, owner : User? = nil, group : Group? = nil, follow_symlinks : Bool = false) : Nil #

Changes the owner of the specified file.

File.chown("/foo/bar/baz.cr", "a_owner", "a_group")
File.chown("/foo/bar", group: "a_group")

Unless follow_symlinks is set to true, then the owner symlink itself will be changed, otherwise the owner of the symlink destination file will be changed. For example, assuming symlinks as foo -> bar -> baz:

File.chown("foo", group: "a_group")                        # changes foo's group to "a_group"
File.chown("baz", group: "a_group", follow_symlinks: true) # changes baz's group to "a_group"

Raises on error.


[View source]
def self.chown?(path : String, owner : User? = nil, group : Group? = nil, follow_symlinks : Bool = false) : Bool #

Same as chown() but instead returns a Bool indicating success.


[View source]