Re: simulation of a "wc" command
- From: Andrew Poelstra <apoelstra@xxxxxxxxxxxxxx>
- Date: Fri, 29 Aug 2008 14:43:28 GMT
On 2008-08-29, s.dhilipkumar@xxxxxxxxx <s.dhilipkumar@xxxxxxxxx> wrote:
Hi
I have never done this excersice, this is just my version of
code. :) i have just checked few basic conditions and it imitates wc
to an extent.
#include<stdio.h>
char find_char(char x)
{
if( '\n' == x)
return 1;
if( ' ' == x)
return 2;
else
return 3;
}
This function can probably be replaced by the standard function
isspace() given in <ctype.h>.
int main(int argc, char* argv[])
{
FILE *fp=NULL;
char prev=0,ch,ctyp;
int wc=0,nl=0,ws=0;
if (argc != 2)
{
printf ("invlid argument \n");
return 1;
}
1 is not guaranteed to be a valid return value from main(). Use
EXIT_FAILURE from <stdlib.h> instead.
fp=fopen(argv[1], "r");
if (fp == NULL)
{
printf("Unable to open the file %s\n",argv[1]);
return 1;
}
while(!feof(fp))
Uh-oh. This will cause a fencepost error - instead, check ch
against EOF (and define it as an int, not a char, to hold this
value) and use feof() to confirm that it really was end-of-file,
not another error.
{
ch = fgetc(fp);
ctyp = find_char(ch);
if(ctyp == 1)
Yuck. Better to explicitly compare ch against ' ' or '\n',
whichever one you meant. Magic numbers are Bad News.
{
if ( prev == 3 )
wc++;nl++;
}
else if(ctyp == 2)
{
if(prev == 3)
wc++;
ws++;
}
This logic looks like I could replace it with the simpler:
if(isspace(ch))
++wc;
while(isspace(ch))
{
if(ch == '\n')
++nl;
++ws;
ch = fgetc(fp);
}
which is clearer IMHO.
Also, don't top-post. Your reply belongs below the text.
--
Andrew Poelstra apoelstra@xxxxxxxxxxxxxx
To email me, use the above email addresss with .com set to .net
.
- References:
- simulation of a "wc" command
- From: hiteshthappa
- Re: simulation of a "wc" command
- From: s.dhilipkumar@xxxxxxxxx
- simulation of a "wc" command
- Prev by Date: Re: C99 portability challenge
- Next by Date: Re: C99 portability challenge
- Previous by thread: Re: simulation of a "wc" command
- Next by thread: structure defintion vs declaration question
- Index(es):
Relevant Pages
|