- File I/O
- Example Program
File.new - Opening A File
The File.new() method is used for opening files.
The format is like this:
[COLOR=#F08070]handle[/COLOR]= File.new [COLOR=#F07080]filename[/COLOR], "[COLOR=#7080F0]mode[/COLOR]"
Where handle is the variable that would be used for the file handle, filename is the string that contains the name of the file to open, and mode is pretty much the reason code for why you want to open the file.
Some values for mode are:
r for reading w for writing; overwrites file if does exist r+ for reading and writing w+ for writing and reading; overwrite file if does exist a appending (adding to the end) a+ appending and reading
handle.sysread - Reading From A File
[COLOR=#F08070]handle[/COLOR].sysread [COLOR=#C07060]n[/COLOR]should read n bytes from file referenced by handle.
The return value is the buffer with the bytes read.
handle.syswrite - Writing To A File
[COLOR=#F08070]handle[/COLOR].syswrite [COLOR=#C08050]buffer[/COLOR]should write buffer to the file referenced by handle.
handle.close - Closing A File Handle
You need to always close file handles after using the files; otherwise you might cause resource leaks in the system.
[COLOR=#F08070]handle[/COLOR].closeshould close the file handle handle.
File.open - Another Way To Open A File
The other way to open a file is using File.open;
With File.open, you don't have to close the file after working on it, you just need the 'do...end' block:
File.open "filename.txt", "w" do |hFile| ...do something... end
hFile, in this case, is the handle to the opened file.
The file handle should get closed by itself.
IO.readlines - Reading All The Lines From A File Using Its Filename
You can also use the IO.readlines() method to read all the lines from a file into an array. Each line read gets its own element in the array.
lines= IO.readlines $0 for i in 0..(lines.length) puts lines[i] end gets
The above code will read and print to the screen all the lines from its own source code file.
$0 means the name of the script file. So if you save that code to file.rb, it would read and print to the screen everything from file.rb .
Okay, that's about enough for us to do something with file I/O, so let's get to the example program.
# Open file test.txt for reading. hFile= File.new "test.txt", "r" # Read 10 bytes from the file. buffer= hFile.sysread 10 # Close the file handle, because we won't be using it any more. hFile.close # Print the buffer to the screen. puts buffer # Open file file.txt for writing. fh= File.new "file.txt", "w" # Write "Hello World!\r\n" to the file. fh.syswrite "Hello World!\r\n" # Close the file handle, because we won't be using it any more. fh.close # Open file log.txt for appending. fh= File.new "log.txt", "a" # Write a line to the log file. fh.puts "File IO Test" # Close the file handle; we won't need that any more. fh.close # Wait for return key press. gets
Hello World Introduction
More About The Language
Edited by RhetoricalRuvim, 27 August 2011 - 10:54 PM.