模拟实现Linux命令-wc

模拟实现linux下一个小命令:wc
这里写图片描述

#include 
#include 
#include 
int main(int argc,char *argv[])
{
    int c=0;
    int l=0;
    int w=0;
    int len=0;
    int i=0;
    int status=0;

    if(argc!=2)
    {
        fprintf(stderr,"usage:./a.out test.c");
        exit(0);
    }

    FILE *fp=fopen("test.c","r");
    if(fp==NULL)
    {
        fprintf(stderr,"can't open!");
        exit(1);
    }

    fseek(fp,0,SEEK_END);
     len=ftell(fp);
    rewind(fp);

    char *buf=(char *)malloc(len+1);
    fread(buf,len,1,fp);

    for( i=0;buf[i];i++)
    {
        c++;
        if(buf[i]=='\n')
        {
            l++;
        }   
        if( !isspace(buf[i]) && status==0)
        {
            w++;
            status=1;
        }
        else if( isspace(buf[i]) )
        {
            status=0;
        }
    }

    printf("c=%d l=%d w=%d\n",c,l,w);


    free(buf);
    fclose(fp);
    fp=NULL;

    return 0;
}

你可能感兴趣的:(Linux,c练习,Linux基础学习)