User can create a File in Ruby with File.new method which is used reading and writing or both operations based on the string and user can also close the method by using the
File.close method. The snippet below demonstrates the creating new file as shown below.
[ruby]
aFile = File.new("filename", "mode")
# ... process the file
aFile.close
[/ruby]
User can open the existing file by using
File.open. In which it will create new file object and assign to a file the only difference between File.open and File.new is the File.open is associated with block but which is not possible with File.new. The code below demonstrates the File.open as shown.
[ruby]
File.open("filename", "mode") do |aFile|
# ... process the file
end
[/ruby]
In order to open the file which have some functions those are listed below.
- r
Which define read only.
- w
Which defines write only.
- a+
Which defines read and write.
The code below demonstrates the sysread method as shown below.
[ruby]
aFile = File.new("input.txt", "r")
if aFile
content = aFile.sysread(20)
puts content
else
puts "Unable to open file!"
end
[/ruby]
Result
By running the above code in command prompt, the output can be obtained as shown in the image below.
The code below demonstrates the syswrite method as shown below.
[ruby]
aFile = File.new("input.txt", "r+")
if aFile
aFile.syswrite("ABCDEF")
else
puts "Unable to open file!"
end
[/ruby]
Result
By running the above code in command prompt, the output can be obtained as shown in the image below.