您的位置:首页 > 运维架构 > Linux

模拟实现Linux命令-wc

2018-02-27 17:18 387 查看
模拟实现linux下一个小命令:wc



#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: