fread
-
To read data from a file in PHP, we call the
freadfunction, passing it a stream resource and an optional number of bytes to read.PHP
$f = fopen('/path/to/foobar', 'r'); $bytes = fread($f, 8); fclose($f);
To read data from a file in Ruby, we first get a
Fileinstance and then call theFile#readinstance method.Ruby
bytes = nil File.open('/path/to/foobar', 'r') do |f| bytes = f.read(8) end
In Rails applications, it’s a best practice to always open a file by passing a block as shown above. For more on this, see fopen.
Notice that we defined
bytesabove the block. Ifbyteswas only defined inside the block, it would not be available below the block. For an explanation of how this works, see our article on Ruby Block Scope.If your example is simple like this one, you can also use the
File.readclass method.Ruby
data = File.read('/path/to/foobar', 8)
see also
Looking for Rails or PHP web application development, integration, and training?
Rails for PHP is brought to you by Maintainable Software. Get custom web applications and personalized training from the authors of the book and website.

