Authors: Alexandre ZANNI
#
Files
#
Creating and opening files
# Create a file
file = File.new("newfile.txt", "w+")
file.close
# File modes
# **r**, read-only, starts at the beginning
# **r+**, read-write, starts at the beginning
# **w**, write-only, override existing files or creates a new file
# **w+**, read-write, override existing files or creates a new file
# **a**, write-only, appends to the end of existing file or creates a new file
# **a+**, read-write, appends or reads to the end of existing file or creates a new file
# Open an existing file
file = File.open('filename.txt', 'w+')
file.close
#
Reading and writing files
# Write into a file
file = File.new("newfile.txt", "w+")
file.puts("some text") # add line break
file.write("some other") # no line break
file.close
# File block
File.open("test.txt", "w+") do |file|
file.puts("test")
end # auto-close
# Read the entire content of a file
puts File.read("file.txt")
# Read a file line by line
File.readlines("file.txt").each do |line|
puts "> #{line}"
end
#
Deleting files
# Delete a file permanently
File.delete("file.txt")
# Check file existence
File.open("test.txt") if File.file?("test.txt")
#
File information
# Size of a file
f1 = File.new("test1.txt", "w")
f1.puts("this is a test")
f1.size # return 15, need open stream
f1.close
# Check if empty
File.zero?("test1.txt") # return false
# Check permissions
File.readable?("test1.txt") # return: true
File.writable?("test1.txt") # return: true
File.executable?("test1.txt") # return: false