[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Should nextfile in BEGINFILE skip ENDFILE?
From: |
Ed Morton |
Subject: |
Re: Should nextfile in BEGINFILE skip ENDFILE? |
Date: |
Sun, 15 Nov 2020 22:54:52 -0600 |
> On Nov 15, 2020, at 10:06 PM, arnold@skeeve.com wrote:
>
> Ed Morton <mortoneccc@comcast.net> wrote:
>
>> I thought that was just saying that given nextfile exists you could write:
>>
>> BEGINFILE {
>> if ( (getline < FILENAME) < 0 ) {
>> nextfile
>> }
>> }
>>
>> or similar to test if you can open the current file, I didn't get that
>> the behavior would automatically change if an error occurred.
>>
>> I have to say I do wish that wasn't the case and nextfile simply behaved
>> the same in a BEGINFILE as anywhere else and caused ENDFILE to be
>> evaluated as it's not clear why skipping ENDFILE would always be
>> desirable,
>
> In the case of a bad file, you'll never get to ENDFILE.
>
>> it's not obvious why puting a nextfile in a BEGINFILE would
>> be related to handling of errors opening files, and it's easy to handle
>> errors opening files using a getline without this, e.g. if nextfile
>> behaved the same in BEGINFILE as everywhere else and I wanted to handle
>> file opening errors gracefully I could just write this clear, brief,
>> simple code:
>>
>> BEGINFILE {
>> bad_file = 0
>> if ( (getline < FILENAME) < 0 ) {
>> print FILENAME, "is a bad file"
>> bad_file = 1
>> nextfile
>> }
>> }
>>
>> ENDFILE {
>> if ( !bad_file ) {
>> do stuff
>> }
>> }
>
> The point is that gawk does this for you. Your code should be
>
> BEGINFILE {
> if (ERRNO) {
> print FILENAME, "is a bad file"
> nextfile
> }
> }
>
> ENDFILE {
> # guaranteed if we reach here that file was good
> do stuff
> }
>
> This is simpler. Remember that gawk already knows if a file
> it wants to open is bad or not; it gives you a hook in BEGINFILE
> to deal with that if you want to, by using nextfile. If you don't
> bother to deal with it, it throws a fatal error.
>
> $ gawk 'BEGINFILE { print "before", FILENAME }' /no/such/file
> before /no/such/file
> gawk: cmd. line:1: fatal: cannot open file `/no/such/file' for reading: No
> such file or directory
>
> Arnold
Ok thanks for explaining it.
Ed