bug-gawk
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [bug-gawk] Is close() better to be used for file reaching the end?


From: Andrew J. Schorr
Subject: Re: [bug-gawk] Is close() better to be used for file reaching the end?
Date: Thu, 31 Jan 2019 16:28:39 -0500
User-agent: Mutt/1.5.21 (2010-09-15)

Hi,

On Thu, Jan 31, 2019 at 03:02:28PM -0600, Peng Yu wrote:
> while(getline < f) {
> do something
> }
> 
> Suppose that I have the above code that read a file. Is it better to
> close the file manually? Or awk will close it automatically once it
> reaches the end of the file?
> 
> close(f)

In fact, gawk will not close the file automatically. Subsequent calls
to getline will continue to return EOF, unless you close the file. If you close
the file, then the next getline will reopen it and start from the beginning.

bash-4.2$ wc /etc/group
 233  233 4648 /etc/group
bash-4.2$ gawk 'BEGIN {while ((rc = (getline < "/etc/group")) > 0) n += rc; 
print n; for (i = 1; i <= 3; i++) print (getline < "/etc/group")}'
233
0
0
0

I think this is explained pretty clearly in the manual:
https://www.gnu.org/software/gawk/manual/html_node/Close-Files-And-Pipes.html

Regards,
Andy



reply via email to

[Prev in Thread] Current Thread [Next in Thread]