www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2000/05/11/07:36:04

From: Hans-Bernhard Broeker <broeker AT physik DOT rwth-aachen DOT de>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: feof(FILE *) NOT portable...
Date: 11 May 2000 11:15:00 GMT
Organization: Aachen University of Technology (RWTH)
Lines: 47
Message-ID: <8fe4nk$ctc$1@nets3.rz.RWTH-Aachen.DE>
References: <8empao$5k6$1 AT nnrp02 DOT primenet DOT com> <390ef9f9$0$72098 AT SSP1NO17 DOT highway DOT telekom DOT at> <8emvhq$7mn$1 AT nnrp03 DOT primenet DOT com> <3 DOT 0 DOT 6 DOT 32 DOT 20000505015633 DOT 007b2210 AT pop DOT crosswinds DOT net> <3 DOT 0 DOT 6 DOT 32 DOT 20000510204858 DOT 007b6e40 AT pop DOT crosswinds DOT net>
NNTP-Posting-Host: acp3bf.physik.rwth-aachen.de
X-Trace: nets3.rz.RWTH-Aachen.DE 958043700 13228 137.226.32.75 (11 May 2000 11:15:00 GMT)
X-Complaints-To: abuse AT rwth-aachen DOT de
NNTP-Posting-Date: 11 May 2000 11:15:00 GMT
Originator: broeker@
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

Thomas J. Hruska <shinelight AT crosswinds DOT net> wrote:
> In a NORMAL
> programming language (anything other than DJGPP) you can read the last
> character, call feof(FILE *), and it will return that it has indeed reached
> the end of file.  

Not in any 'NORMAL' programming language that has to read Unix files,
like C. DJGPP is not a language, it's a compiler implementing one
language, and does behave exactly as required.

To do what you want, the program would have to be
prescient. 'End-of-File' can only reliably be detected by trying to
read something, and finding there's nothing left to read. Otherwise,
reading from stdin or other externally driven 'files' would never
work.

>   do
>   {
>     x[0] = fgetc(fp);
>     str = (char *)realloc(str, strlen(str) + 2);
>     strcat(str, x);
>   } while (!feof(fp) && x[0] != 10);

This loop is contrasting to the usual C idioms, and, unsurprisingly,
caught a bug an doing so. The idiom would be using an int variable to
read to, and compare that to EOF, before assigning the result to a
char-type variable, but to stay closer with your current style, you'ld
have to write

  do
  {
    x[0] = fgetc(fp);
    if (feof(gp))
      break;
    str = (char *)realloc(str, strlen(str) + 2);
    strcat(str, x);
  } while (!feof(fp) && x[0] != '\n');

Also note the change from a magical number '10' to the character '\n'.

Actually, truely idiomatic progamming would use 'fgets()', instead of
fgetc(), for this, avoiding hundreds of calls to realloc(), by using
an appropriate buffer size.

-- 
Hans-Bernhard Broeker (broeker AT physik DOT rwth-aachen DOT de)
Even if all the snow were burnt, ashes would remain.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019