This section describes a
Two special kinds of rule,
you “hooks” into
gawk’s command-line file processing loop.
As with the
END Special Patterns),
BEGINFILE rules in a program execute in the order they are
gawk. Similarly, all
ENDFILE rules also execute in
the order they are read.
The bodies of the
BEGINFILE rules execute just before
gawk reads the first record from a file.
is set to the name of the current file, and
FNR is set to zero.
Prior to version 5.1.1 of
gawk, as an accident of the
$0 and the fields retained any previous values
they had in
BEGINFILE rules. Starting with version
$0 and the fields are cleared, since no record has been
read yet from the file that is about to be processed.
BEGINFILE rule provides you the opportunity to accomplish two tasks
that would otherwise be difficult or impossible to perform:
You do this by checking if the
ERRNO variable is not the empty
string; if so, then
gawk was not able to open the file. In
this case, your program can execute the
nextfile Statement). This causes
gawk to skip
the file entirely. Otherwise,
gawk exits with the usual
gawkhas started processing the file. (This is a very advanced feature, currently used only by the
ENDFILE rule is called when
gawk has finished processing
the last record in an input file. For the last input file,
it will be called before any
ENDFILE rule is executed even for empty input files.
Normally, when an error occurs when reading input in the normal
input-processing loop, the error is fatal. However, if a
rule is present, the error becomes non-fatal, and instead
is set. This makes it possible to catch and process I/O errors at the
level of the
next statement (see The
next Statement) is not allowed inside
BEGINFILE or an
ENDFILE rule. The
statement is allowed only inside a
BEGINFILE rule, not inside an
getline statement (see Explicit Input with
getline) is restricted inside
ENDFILE: only redirected
getline are allowed.
In most other
awk implementations, or if
gawk is in
compatibility mode (see Command-Line Options), they are not special.