gawk: Empty Files
1
1 10.3.4 Checking for Zero-Length Files
1 -------------------------------------
1
1 All known 'awk' implementations silently skip over zero-length files.
1 This is a by-product of 'awk''s implicit
1 read-a-record-and-match-against-the-rules loop: when 'awk' tries to read
1 a record from an empty file, it immediately receives an end-of-file
1 indication, closes the file, and proceeds on to the next command-line
1 data file, _without_ executing any user-level 'awk' program code.
1
1 Using 'gawk''s 'ARGIND' variable (⇒Built-in Variables), it is
1 possible to detect when an empty data file has been skipped. Similar to
1 the library file presented in ⇒Filetrans Function, the following
1 library file calls a function named 'zerofile()' that the user must
1 provide. The arguments passed are the file name and the position in
1 'ARGV' where it was found:
1
1 # zerofile.awk --- library file to process empty input files
1
1 BEGIN { Argind = 0 }
1
1 ARGIND > Argind + 1 {
1 for (Argind++; Argind < ARGIND; Argind++)
1 zerofile(ARGV[Argind], Argind)
1 }
1
1 ARGIND != Argind { Argind = ARGIND }
1
1 END {
1 if (ARGIND > Argind)
1 for (Argind++; Argind <= ARGIND; Argind++)
1 zerofile(ARGV[Argind], Argind)
1 }
1
1 The user-level variable 'Argind' allows the 'awk' program to track
1 its progress through 'ARGV'. Whenever the program detects that 'ARGIND'
1 is greater than 'Argind + 1', it means that one or more empty files were
1 skipped. The action then calls 'zerofile()' for each such file,
1 incrementing 'Argind' along the way.
1
1 The 'Argind != ARGIND' rule simply keeps 'Argind' up to date in the
1 normal case.
1
1 Finally, the 'END' rule catches the case of any empty files at the
1 end of the command-line arguments. Note that the test in the condition
1 of the 'for' loop uses the '<=' operator, not '<'.
1