The proper way to open()

David Cantrell david at cantrell.org.uk
Mon Jan 30 17:00:32 GMT 2012


On Mon, Jan 30, 2012 at 04:46:00PM +0000, Roger Burton West wrote:

> What's a good way of opening a file as read-only, and failing if it
> doesn't exist? open() just returns a handle that's not obviously
> invalid, which strikes me as odd behaviour.

Why not just check the return value from open()?

$ perl -e 'open(FOO, "doesnt_exist") || die("Bad programmer, no bikkit!\n")'
Bad programmer, no bikkit!

But note that this is indistinguishable from it failing to open because,
eg, you don't have permission, so also check $! which gives a useful
string in string context and whatever C's errno is in numeric context.

Or check for file existence / readability first, using -whatever.

-- 
David Cantrell | A machine for turning tea into grumpiness

    Vegetarian: n: a person who, due to malnutrition caused by
      poor lifestyle choices, is eight times more likely to
      catch TB than a normal person


More information about the london.pm mailing list