:: Re: [DNG] gcc error: "error: unkno…
Top Pagina
Delete this message
Reply to this message
Auteur: Rainer Weikusat
Datum:  
Aan: dng
Onderwerp: Re: [DNG] gcc error: "error: unknown type name,,, ‘GtkObject’"
Edward Bartolo <edbarx@???> writes:
> I think, the fgets outside the loop is not required. I think it can be
> done this way:
>
> #include <stdio.h>
>
> main()
> {
> FILE * fp;
> char str[1024];
>
> fp = popen ("/usr/lib/netman/bin/backend 6", "r");
>
> if (fp == NULL) return -1;
>
>   while (!feof (fp))
>   {
>     fgets (str, 1024, fp);
>     printf ("%s", str);
>   }
>   pclose (fp);
>   return 0;
> }


This doesn't work: It prints the last input line twice.

Rationale: feof(fp) won't be true until a read operation actually hit
the end of the file. This means it won't be true after fgets read the
last line. fgets will then be called again for the next iteration,
causing it to detect the EOF. This leaves the contents of str unmodified
which will thus get printed again. The simple way to avoid that would be
to handle the return value of fgets:

--------
#include <stdio.h>

int main(void)
{
FILE * fp;
char str[1024];

fp = popen ("cat /etc/passwd", "r");

if (fp == NULL) return -1;

  while (fgets (str, 1024, fp))
    printf ("%s", str);


pclose (fp);
return 0;
}
--------

Omitting the return value of a function for a default of 'int' isn't
standard-conforming C anymore more and using () as synonym for "whatever
the caller desired to pass" is 'an obsolescent feature' (although
sometimes useful). The C way to denote an empty argument list is (void),
() means the same in C++.