strings命令的实现 2014-06-02 00:17 355人阅读 评论(0) 收藏

本程序实现从文件中提取连续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.
",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=='	')&&last < BUFSIZE-1)//标准strings命令也接受'	'
     buf[last++] = c;
     else 
     {
       if (last >= 4) 
        {
          buf[last] = '';
          printf("%s
", buf);
         }
       last = 0;
     }
     if (c == EOF) break;
    }
}









版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/luo-peng/p/4646258.html