parm530
1/31/2018 - 4:34 PM

File Input and Output

File System input and output with ruby

Output

  • Executed using print and puts statements

Input (user)

  • Executed using gets statement
  • Used in conjuction with chomp to remove line return: input = gets.chomp

File seperators

  • In unix/mac: /
  • In windows: \
  • Ruby uses a general way so you don't have to specify which character to use:
#using the File class:
File.join("users", "documents", "me.rb")
#output is 
# users/documents/me.rb for mac and
# users\documents\me.rb for windows

#to get an absolute path (from the root), first arg is empty string
File.join("","...", "...")

Change Permission (linux/mac)

chmod

Change Owner (linux/mac)

chown

Paths

  • absolute path: path from the root folder to the file, begins with a forward slash

  • relative path: path from where we are now to where the file lives

  • ruby gives us a variable that gives us the path to the file we are in now: _FILE_

    • to get to the absolute path: File.expand_path(_FILE_)
    • to get the directory name of the file: File.dirname(_FILE_)
  • to get the name of the file: puts _FILE_ => relative path


Accessing a file

  • file = File.new(file_name, mode_to_open_file_in)
    • Ex) file = File.new('parm.text', 'w')
    • ALWAYS file.close after finishing with file!

Alternative way:

  • Using File.open which creates a file object if it cannot find one and will close the file once the code block has ended (so you won't need to close it manually)
File.open('parm.text','r') do |fi|
  #some code in here
end
  • other second argument options: w, r, a, w+, r+, a+
    • r: read from the start, file must already exist
    • w: writes from the start, if the file doesn't exist it will create it, if it does exist, it will wipe the file clean and then apply the text to the beginning
    • a: append to the end of the file
    • r+: read and write to a document, from the start without clearing the page.
    • w+: read and write to a document by clearing the page.
    • a+: read and write to the document, by appending new content to the end.

Writing to a file

  • The following are ways to write to a file:
file = File.new(...)

file.puts "abcd"      #returns nil
file.print "abcd"     #returns nil & no line return
                      #to use a line return with print:
file.print "hi\n"     #use the escape charater

file.write "abcd"     #returns the NUMBER of characters added to the file
file << "abcd"        #returns the file object

file.close            #ALWAYS CLOSE!


Reading Content from files

  • You can obtain content from a file in the following way:
  • gets returns 1 line, more specifically, it returns everything from the current position to the end of the line!

file.gets             #gets 1 line
file.gets.chomp       #gets 1 line without the line return

file.read(integer)    #returns number of characters
                      #line return character also counts as a character
                      
#Looping through each line
file.open('filename.txt', 'r') do |file|
  while line = file.gets
    puts "**" + line.chomp.reverse + "**"
  end
end

#OR, ALTERNATIVELY: using method: each_line

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


File Pointer

  • Works like the cursor in a document
  • If a file pointer is in a certain spot, it doesn't insert text, it overwrites text!
  • You can write to files and read from files
  • You can check the file position: file.pos
  • You move the pointer by reading in characters, the number of characters read is equal to the number of characters the file pointer moves:
file.read 5
file.pos #returns 5
  • You can assign the file pointer to any location: file.pos = 13
    • If you read, you will start at the 13th character
  • file reached the end of file? file.eof?, returns true if at end of file
  • To jump back to the beginning of the file:
file.pos = 0
#OR
file.rewind
  • Move forward from where you are to a certain number of characters file.pos += 6
  • Move backward from where you are to a certain number of characters file.pos -= 2
  • You can move (write) beyond the end of the file: file.pos += 100
    • file.write "xyz" will insert "xyz" at the new position, but ruby will fill in the spaces with nil or \000 characters

Renaming and Deleting Files

  • To rename a file: File.rename(oldname, newname)
  • To delete a file: File.delete(filename)
  • To perform rename and delete actions on a file, you'll need to make sure that the file itself contains write access, you'll also need write permissions on the directory that contains the file!!

Copying a file

  • To copy a file, you will need to load a library that ships with ruby but is not loaded when ruby is loaded: require 'fileutils'
  • Then: FileUtils.copy("filetobecopied.txt", "copied.txt")

Examining a file

  • File.exist?(file): checks if it exists
  • File.true?(file): checks to see if the file is indeed a file
  • File.directory?(file): checks to see if the file is a directory
  • File.readable?(file)
  • File.writable?(file)
  • File.executable?(file)
  • File.size(file): returns number of bytes of the file
  • File.dirname(file): returns directory name
  • File.ext(file): returns file extension
  • File.mtime(file): returns last modified time for the file, 'w'
  • File.atime(file): returns last time the file was accessed, 'r','w'
  • File.ctime(file): returns last time the file's status was changed, NOT WHEN THE FILE WAS CREATED! 'r','w', changes in permissions, groups or owners, try not to use it!
  • Examining a file that you are working on, use the stat (instance) method!
    • myfile.stat.size or myfile.stat to retrieve a stat object with the stats of the file

Working with Directories

  • List entries: Dir.entries(arg): arg is the location of where to list the entries for
    • Returns a ruby array (can pass in a code block)
    • Dir.foreach(arg): creates the iteration, just pass in the code block code
  • Dir.mkdir(name_of_directory): creates new directory
  • Dir.delete(name_of_directory): deletes the directory (if the directory that contains it has write permissions AND directory has to be empty!)
    • To empty the directory, you can loop through it and delete each one
    • Use the FileUtils library
  • Dir.glob('Users/parms/Documents/TVSHOW/Friends/S1*.mkv') will retrieve all files in the path specified that end with .mkv
  • FileUtils.mv(current_file_path, new_path)