Return to Snippet

Revision: 20137
at November 11, 2009 21:20 by chrisaiv


Updated Code
=begin
'r' = Read from start (it must exist beforehand)
'w' = Start a new file, Write from the start but destroys any existing data (very distructive) 
'a' = Append / Write from end
'r+' = Read and write without being destructive


#File.new( 'file_name.extension', 'r|w|a|r+|w+|a+' )
file = File.new( 'file_example.txt', 'w' )

#You must close to free up the resources
file.close

#Open a file, pass a block of instructions, and it will open and close on its own
File.open( 'file_example.txt', 'r') do |file|
  #Read data from the file
end

=end

file = File.new("file_example.txt", "w")
#Various ways to print to a file
file.puts "Ruby"
file.print "programing\n"
file.write "is"
file << "fun"
#Close method is required to actually save 
file.close

File.open("file_example.txt", "r") do |file|
  #While there is a new line
  while line = file.gets
    puts "** " + line.chomp.reverse + " **"
  end
end

File.open("file_example.txt", "r") do |file|
  file.each_line { |line| puts line.upcase }
end


### More File class methods ###

file = "file_example.txt"

#See if this file exists
puts File.exist?(file)
#Is this a file? 
puts File.file?(file)
#IS this a directory?
puts File.directory?(file)
#Readable?
puts File.readable?(file)
#Writable?
puts File.writable?(file)
#Executable?
puts File.executable?(file)
#File Size?
puts File.size(file)
#Just get me what's in the ned
full_path =  File.expand_path(file) 
puts File.basename(full_path)
#Find the extension
puts File.extname(file)
#Last time it was accessed
puts File.atime(file)
#Last modified time
puts File.mtime(file)
#Last status change time.  Read/Write/Owner/Group/or Permissions
puts File.ctime(file)

Revision: 20136
at November 8, 2009 20:36 by chrisaiv


Initial Code
=begin
'r' = Read from start (it must exist beforehand)
'w' = Start a new file, Write from the start but destroys any existing data (very distructive) 
'a' = Append / Write from end
'r+' = Read and write without being destructive


#File.new( 'file_name.extension', 'r|w|a|r+|w+|a+' )
file = File.new( 'file_example.txt', 'w' )

#You must close to free up the resources
file.close

#Open a file, pass a block of instructions, and it will open and close on its own
File.open( 'file_example.txt', 'r') do |file|
  #Read data from the file
end

=end

file = File.new("file_example.txt", "w")
#Various ways to print to a file
file.puts "Ruby"
file.print "programing\n"
file.write "is"
file << "fun"
#Close method is required to actually save 
file.close

File.open("file_example.txt", "r") do |file|
  #While there is a new line
  while line = file.gets
    puts "** " + line.chomp.reverse + " **"
  end
end

File.open("file_example.txt", "r") do |file|
  file.each_line { |line| puts line.upcase }
end

Initial URL


Initial Description


Initial Title
Ruby: Reading from Files + File Class Methods

Initial Tags
file, ruby

Initial Language
Ruby