Deutsch   English   Français   Italiano  
<vobled$tem3$1@dont-email.me>

View for Bookmarking (what is this?)
Look up another Usenet article

Path: ...!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!eternal-september.org!.POSTED!not-for-mail
From: Janis Papanagnou <janis_papanagnou+ng@hotmail.com>
Newsgroups: comp.lang.c
Subject: Re: Buffer contents well-defined after fgets() reaches EOF ?
Date: Mon, 10 Feb 2025 02:40:28 +0100
Organization: A noiseless patient Spider
Lines: 36
Message-ID: <vobled$tem3$1@dont-email.me>
References: <vo9g74$fu8u$1@dont-email.me> <8734gmpotb.fsf@bsb.me.uk>
MIME-Version: 1.0
Content-Type: text/plain; charset=windows-1252
Content-Transfer-Encoding: 7bit
Injection-Date: Mon, 10 Feb 2025 02:40:30 +0100 (CET)
Injection-Info: dont-email.me; posting-host="7ae7436750940773d2334410c5fdf1e5";
	logging-data="965315"; mail-complaints-to="abuse@eternal-september.org";	posting-account="U2FsdGVkX1+bOoJpkw+oDziD4sIqevPz"
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101
 Thunderbird/45.8.0
Cancel-Lock: sha1:lhg4QaKz69MPsYXf4XsGsmBG7ZM=
In-Reply-To: <8734gmpotb.fsf@bsb.me.uk>
Bytes: 2401

On 10.02.2025 02:32, Ben Bacarisse wrote:
> Janis Papanagnou <janis_papanagnou+ng@hotmail.com> writes:
> 
>> To get the last line of a text file I'm using
>>
>>     char buf[BUFSIZ];
>>     while (fgets (buf, BUFSIZ, fd) != NULL)
>>         ;   // read to last line
>>
>> If the end of the file is reached my test shows that the previous
>> contents of 'buf' are still existing (not cleared or overwritten).
> 
> Something that has not yet come up (as far as I can see) is that you
> might need to handle an empty file.  In such a case, nothing gets
> written and fgets returns NULL right away.  Processing buf in this
> situation is then undefined.

I haven't considered that at all because my context is very specific;
it's just three text lines (a comment line, an empty separator line,
and a line with the payload data that I'm interested in). If there's
a file it will have exactly these three lines (and all correctly and
consistently terminated).

> 
> One way to handle this is to put into buf something that can't get read
> by fgets.  Two newlines is a good candidate:
> 
>   char buf[BUFSIZE] = "\n\n";
> 
> You can then test for that if need be, though of course it all depends
> on what your application is doing.

Thanks for pointing it out and for the suggestion.

Janis