fread

  • To read data from a file in PHP, we call the fread function, 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 File instance and then call the File#read instance 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 bytes above the block. If bytes was 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.read class method.

    Ruby

    data = File.read('/path/to/foobar', 8)

    see also

fputs fseek

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.