Using blocks in C (with File.open)

Hi:

I have written some code in Ruby to parse a file and yield
items inside the file. It looks something like this:

def each(file)_
File.open(file) { |f|
# Do work here
}
end

To speed this up, I have written this in C. However, my original
version had the File.open() {} code in Ruby.
I am now writing that in C, don’t know how to use the block
methodology so the file will automatically close.

Below is what I currently have:

static VALUE
each(self, filename)
VALUE self, filename;
{
VALUE f = rb_file_open(filename, rb_str_new2(“r”));

/* do work here */

rb_io_close(f);

}

Can someone provide sample code of how use File.open and
blocks in C?

Thanks

···


Jim Freeze

Money is better than poverty, if only for financial reasons.

Can someone provide sample code of how use File.open and
blocks in C?

    static VALUE
    do_work_here(file)
        VALUE file;
    {
        /* do work here */
        return Qnil;
    }

  static VALUE
  each(self, filename)
  VALUE self, filename;
  {
    VALUE f = rb_file_open(filename, rb_str_new2("r"));

       return rb_ensure(do_work_here, f, rb_io_close, f);

  }

Guy Decoux