Error checking on File I/O

J

Joe Minicozzi

This is kind of an oddball question, but it's been bugging me for a while.
How does one check for an error when reading a file?

Unless I've misread the documentation (about 100 times), getting undef from
a readline means EOF _or_ error. I've been working with Perl since version
5 came out and the only way I've found to discern between EOF and error is
to use IO::Handle::error. I've been using the following code to do this:

# The following bit of skullduggery is used to load as little of the IO
module
# as possible while defining &IO::Handle::error, which is defined in the XS
# part of the IO module, version 1.20.
use IO 1.20 () ;
BEGIN
{
# Check that &IO::Handle::error was defined.
die "$ProgName: &IO::Handle::error not defined by IO XS module;"
unless defined &IO::Handle::error ;
}
....
$line = readline HANDLE ;

# Check for read error. This uses Perl's *foo{THING} syntax.
# (See Making References in the perlref manpage.)
if (*HANDLE{IO}->error()) # read error
{
...
}
else # EOF
{
...
}

Assuming I haven't missed something, if there are any Perl historians,
language lawyers or source code gurus out there, I'd like to know why it's
not easier to error check a readline. Error checking a print is much
simpler -- the return value of print indicates success or failure. However,
error checking a write would appear to require use of IO::Handle::error too;
Perl documentation does not indicate any return value. (Thankfully, I
almost never use write.)
 

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,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top