Tuesday 16 April 2013

Basic File operations in Ruby


This post will show different file operations under RUBY. Ruby is an open source programming language developed by Yukihiro Matsumoto.

The file operations shown are:
  • Reading file data each one by one
  • Read file data and print it on screen
  • Read file data using custom delimiter with gets
  • Reading first 10 bytes from file
  • Read first 4 bytes and print it under separate lines
  • Reading file into string data
  • Finding position withing a file
  • Writing to a file


The following files are used for below executed program:

file1.txt
Hi, my name is amit
Working at Website

file2.txt
This is second file...

file3.txt
Amit, IT, 24
Ajay, HR, 25

file4.txt  (the following content will be written to this file)
This is a test



# code (http://www.techterabyte.com)
puts "Start with reading file data each one by one..."
File.open("file1.txt","r").each { |line| puts line }

puts "-----------"
puts "Now, read file data and print it on screen..."
f = File.new("file2.txt","r")
puts f.gets
f.close

puts "-----------"
puts "Read file data using custom delimiter with gets..."
File.open("file3.txt","r")  do |f|
4.times {puts f.gets}
end

puts "-----------"
puts "Read first 10 bytes from file..."
File.open("file3.txt") do |f|
   puts f.read(10)
end

puts "-----------"
puts "Read first 4 bytes and print it under separate lines..."
File.open("file3.txt") do |f|
3.times {puts f.read(4)}
end

puts "-----------"
puts "Reading file3.txt into string data..."
data =  File.read("file3.txt")
puts data

puts "-----------"
puts "Finding position withing a file..."
f2= File.open("file2.txt","r")
print "Current position:"
puts f2.pos
f2.pos = 8
puts f2.gets
print "Now, Current position:"
puts f2.pos

puts "-----------"
puts "Writing to a file..."
File.open("file4.txt", "w") do |f|
f.puts "This is a test"
end
puts "text written correctly"

puts "-----------"


# code (http://www.techterabyte.com)






The output is shown here i.e $ruby program1.rb

Start with reading file data each one by one...
Hi, my name is amit
Working at Website
-----------
Now, read file data and print it on screen...
This is second file...
-----------
Read file data using custom delimiter with gets...
Amit, IT, 24
Ajay, HR, 25
nil
nil
-----------
Read first 10 bytes from file...
Amit, IT, 
-----------
Read first 4 bytes and print it under separate lines...
Amit
, IT
, 24
-----------
Reading file3.txt into string data...
Amit, IT, 24
Ajay, HR, 25
-----------
Finding position withing a file...
Current position:0
second file...
Now, Current position:23
-----------
Writing to a file...
text written correctly
-----------


This way you can learn different file operations within a single program at beginner level.

No comments:

Post a Comment