Click to See Complete Forum and Search --> : problem with cat-like program (spit.c)


ubaka
01-17-2003, 07:11 AM
yo, here's my version of cat. it's very simple and does'nt take in any options or switches.


/* a cat-like program without options*/
#include <stdio.h>
#include <errno.h>

main(int argc, char *argv[])

{
FILE *fpt;
int i;

if (argc > 1) {
for (i=2; i<=argc;i++)
{
if ((fpt = fopen(argv[i-1], "r")) == NULL)
{
perror(argv[i-1]);
continue;
}
else
while (!feof(fpt))
putchar(getc(fpt));
printf("\n");
fclose(fpt);
}
}
else
fprintf(stderr, "usage: spit [filename]...\n");
return(0);
}



the problem here is after i run the executable, i get a funny looking character at the end of each file. can anybody help me debug?

goon12
01-17-2003, 09:20 AM
Im not to familiar with feof() but from reading the man page maybe you need to call clearerr() in there some where to remove the EOF indicator.

wapcaplet
01-17-2003, 09:40 AM
It might work to just make it a do-while loop instead:


do
putchar(getc(fpt));
while (!feof(fpt))


I think the problem with the way it is, it says "At end of file? No, so print the next character. Oops, that was the end of the file." Though, doing it this way instead might cause trouble if you try to run it on an empty file. Maybe you could put an if statement in the loop to make sure it's not EOF before you print it out.

goon12
01-17-2003, 09:50 AM
If I were to do something like cat I would use something like this:


FILE *show;
char c;
..
open file for reading
...
while( ( c = getc(show) ) != EOF )
{
fputc(c, stdout);
}