Groovy hepcat RoS was jivin' in comp.lang.c on Sun, 9 Dec 2007 5:51 pm.
It's a cool scene! Dig it.
In data Fri, 07 Dec 2007 00:52:19 +1100, Peter 'Shaggy' Haywood
scrisse:
so what is right?
while(1)
{
c = getchar();
if( feof(stdin) || ferror(stdin) ) break;
putchar(c);
}
or
while(1)
{
c = getchar();
if( feof(stdin) ) break;
putchar(c);
}
while(1)
{
c = getchar();
if( ferror(stdin) ) break;
putchar(c);
}
or no one of above
Neither of the scenarios you have given. But I have shown you what to
do. Please read the portion of my previous reply that I have quoted
above (beginning with "What you should be doing is this:"). Here's how
it works:
while(EOF != (c = getchar()))
Here we read in a byte with getchar(). If the read fails, getchar()
returns EOF (which is a negative integer constant that compares unequal
to any valid character value). Each iteration of the loop, its
controlling expression tests for this value and, if EOF is detected,
quits the loop without entering the body.
{
putchar(c);
}
Here in the body of the loop (if entered), all we do is output the
character.
It may help you to understand what's going on if I write it a slightly
different way. The loop as shown above is equivalent to this:
c = getchar();
while(EOF != c)
{
putchar(c);
c = getchar();
}
First we read a character. Next we test whether the read succeeded by
testing for EOF. If the read was successful, the body is entered, and
we output the character then read another. We go back to the top of the
loop and test whether that read was successful. If so, we enter the
body, output the character and read another. And so on.
if(!feof(stdin))
Once we've quit looping, we then use feof() to test for an end of file
condition. If feof() does not return true, then we're not at the end of
the file/stream. In that case, the read failure must have been due to
an error, so we handle it:
{
/* File read error: handle it somehow. */
}
Alternatively, you could use ferror() to test for an error in the
stream, rather than using feof(). This is the method I prefer.
if(ferror(stdin))
{
/* File read error: handle it somehow. */
}
This approach also works with functions that read more than one byte
at a time, such as fprintf() and fread(). For example:
char buf[100];
while(NULL != fgets(buf, sizeof buf, stdin))
{
fputs(buf, stdout);
}
if(ferror(stdin))
{
/* File read error: handle it somehow. */
}