Skip to content

Instantly share code, notes, and snippets.

@julioterra
Created October 7, 2011 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julioterra/1269660 to your computer and use it in GitHub Desktop.
Save julioterra/1269660 to your computer and use it in GitHub Desktop.
IO: sketch that tests different methods for reading data from files one byte at a time.
# filename: files_bytes.rb
# sketch that tests different methods for reading data from files one byte at a time.
# open file to read
puts
puts "Creating a reference to file input stream"
f = File.new("../chapter_11/regex_scan.rb")
# find out what approach to use to read the file
puts "Select a byte-based approach to read the file:"
puts " 1) getc method"
puts " 2) getbyte method"
puts " 3) readchar method"
puts " 4) readbyte method"
input = STDIN.gets.to_i
puts
# if input was 1 then getc read method
if input == 1
puts "** GETC method: \"print char while (char = f.getc)\"\n"
char = ""
print char while (char = f.getc)
# if input was 2 then getbyte each method
elsif input == 2
puts "** GETBYTE method: \"print char while (char = f.getbyte)\" \n"
char = ""
print char while (char = f.getbyte)
# if input was 3 then readchar get method
elsif input == 3
puts "** READCHAR method: \"print char while (char = f.readchar)\"\n"
line = ""
char = ""
print char while (char = f.readchar)
# if input was 4 then use readbyte method
elsif input == 4
puts "** READBYTE method: \"print char while (char = f.readbyte)\"\n"
line = ""
char = ""
print char while (char = f.readbyte)
# if input did not match then display error message
else
puts "** ERROR: your input didn't make sense"
end
puts
# close the file
f.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment