本程序实现从文件中提取连续4个以上的可打印字符。模仿linux中string命令
#include <stdio.h>
#include<stdlib.h>
#include <ctype.h>
#define BUFSIZE 4096
void strings(FILE*fp);
int main(int argc,char*argv[])
{
FILE* fp;
if(argc==1)
{
fp=stdin;
strings(fp);
}
else
{
int i=1;
for(;i<argc;i++)
{
if((fp=fopen(argv[i],"r"))==NULL)
{
fprintf(stderr,"open %s error.\n",argv[i]);
continue;
}
strings(fp);
close(fp);
}
}
return 0;
}
void strings(FILE*fp)
{
int c;
char buf[BUFSIZE];
int last = 0;
while(1)
{
c = getc(fp);
if ((isprint(c)||c=='\t')&&last < BUFSIZE-1)//标准strings命令也接受'\t'
buf[last++] = c;
else
{
if (last >= 4)
{
buf[last] = '\0';
printf("%s\n", buf);
}
last = 0;
}
if (c == EOF) break;
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。