Irrwahn Grausewitz <irrwahn33@freenet.de> wrote in message news:<sg0lsvc7a0p0lmafc2eujt9o6j052aghn6@4ax.com>. ..[color=blue]
>
spawn@rloteck.com (Rafael) wrote:[color=green]
> > Hello Everyone,
> >
> > I need some major help with this code I have for a file viewer. I
> > need it to stop at the 24th line. What Syntax do I need for this to
> > happen?
> >
> > Here is the code....
> >
> > #include <stdio.h>
> > #include <stdlib.h>[/color]
>
> #include <string.h> /* for strchr(), see below */
> #define NUM_LINES 24 /* see below */
>[color=green]
> >
> > int main(int argc, char *argv[])
> > {
> > int i;
> > FILE *fp;
> > char buf[24];
> >
> > if(argv[1]==NULL)
> > {
> > printf("ERROR: Please enter a file name afer char.exe or
> > char.\n");
> > system("PAUSE");
> > }
> >
> > else
> > {
> > fp = fopen(argv[1],"r");
> > while (!feof(fp))[/color]
>
> That's not the recommended way to iterate through a file.
>[color=green]
> > {
> > puts(buf);[/color]
> You are printing the contents of buf before having filled it with
> sensible data. IOW: you print garbage the first time your loop runs.
>[color=green]
> > fgets(buf,sizeof(buf)-1,fp);[/color]
> You don't need to subtract one from the buffer size.
>[color=green]
> >
> > }[/color]
>
> Since you have already declared a variable 'i', you could use it
> to count the lines and change the loop to:
>
> i = 0;
> while ( i < NUM_LINES && fgets( buf, sizeof buf, fp ) )
> {
> fputs( buf, stdout );
> if ( strchr( buf, '\n' ) )
> ++i;
> }
>
> Note the use of fputs, otherwise two newline characters would be
> written after each line: the one read from file by fgets and the
> one automatically appended by puts. Also note the use of the
> #define'd constant NUM_LINES instead of the 'magic number' 24.
>
> The "if (strchr( ...))" construct ensures that the counter is
> incremented only after a whole line has been read. BTW, you may
> consider to use a bigger buffer.
>[color=green]
> >
> > }
> >
> > return 0;
> >
> > }[/color]
>
> Another solution: forget about the buffer and read/write
> character-wise, incrementing the line counter every time you hit
> '\n'.
>
> HTH. Now, what do I get for doing your homework? ;-)
>
> Regards[/color]
Thanks dude, you are the boom......: )
Rafael