[Subject Prev][Subject Next][Thread Prev][Thread Next][Subject Index][Thread Index]

Re: getc() and fgetc()



Thats quite elaborate a reply. thanks a lot.

one more thing.
1) we all have seen, at least me for the past 3 years, that if we give a
character input where an integer was expected, the prog goes for an infinite
joy ride.
2) i also read that scanf can skip white spaces, tabs, line feeds and others
if you want it to and thus can go into "an infinite loop" if it cannot scan
what it was asked to (char for an integer, for instance).
how do i make sense of 1) and 2). Binand definitely has a nice reply, even
though hez not a help desk for linux ;-)

Regards
Rahul
~~~~~~~~~~~~~~~~~~~
In a world without fences...
who needs gates?
~~~~~~~~~~~~~~~~~~~

----- Original Message -----
From: "Binand Raj S." <binand@xxxxxxxxxxxxxxxxxxxxx>
To: <linux-india-programmers@xxxxxxxxxxxxxxxxxxxxx>
Sent: Sunday, March 25, 2001 1:42 PM
Subject: Re: [LIP] getc() and fgetc()

> That is the essential difference. This means that stdio.h might implement
> getc() as a macro, so taking its address is not portable. If you need a
> pointer to a function that takes one argument of type FILE * and returns
> an int (;-), then you cannot portably use getc(), you will have to use
> fgetc() which is guaranteed to be a function.
>
> So, this is not portable:
>
> int (*func)(FILE *) = getc;
>
> whereas this is:
>
> int (*func)(FILE *) = fgetc;
>
> [Note: This difference also comes in if you dlopen() libc and try to
> locate getc() and fgetc() in there via dlsym()].
>
> Another difference is that getc() might evaluate its argument multiple
> times, so if you have an array of FILE * pointers, then code like this
> to read one character from each of them is bad:
>
> FILE **arr; /* array [10] of FILE * pointers */
> int i = 0, c[10];
> while (i < 10) {
>    c[i++] = getc(*arr++);
> }
>
> (Horrible, but you get the idea)
>
> Whereas it is perfectly alright to use fgetc() in the above.
>
> Here is an implementation of getc() (from /usr/lib/bcc/include/stdio.h)
that
> exhibits all the above points:
>
> #define getc(stream) \
>   (((stream)->bufpos >= (stream)->bufread) ? fgetc(stream): \
>     (*(stream)->bufpos++))
>
> This evaluates stream thrice.
>
> Binand