Using blocks in C (with File.open)

J

Jim Freeze

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
 
T

ts

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

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

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

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

J> }



Guy Decoux
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,790
Messages
2,569,637
Members
45,346
Latest member
EstebanCoa

Latest Threads

Top