统计文本文件字符(C语言)

统计txt文件中字符数、单词数、行数

  • 主体思路
    • 利用c的命令行参数传递用户指令
     if(argc < 3)
    {
        printf("Usage ./wc.exe [-c] [-w] [-l] FILE [-o] Outfile");
        exit(0);
    }
    
    for(int count = 1; count < argc; count++)
    {
        //判断必需参数
        if(!strcmp(argv[count], "-c"))
        {
            c = 1;
            //Method1
        }
        else if(!strcmp(argv[count] ,"-w"))
        {
            w = 1;
        }
        else if(!strcmp(argv[count] ,"-l"))
        {
            l = 1;
        }
        else
        {
        //搜索输入文件名
            inputfile = argv[count];
            break;
        }
    
    }   
    • 从测试文件读取内容
    fpread = fopen(inputfile,"r");
    fread(instr,sizeof(char),Maxchar,fpread);
    fclose(fpread);
    • 利用函数处理字符
      • 字符处理函数
      /*
      **字符数统计
      */
      int Charnum(char* str)
      {
          int totalchar=0;
          while(*str++ != '\0')
          {
              totalchar++;
          }
          return totalchar;
      
      }
      • 文本行处理函数
      /*
      **行数统计
      */
      int Linenum(char* str)
      {
          int linenum = 0;
          while(*str != '\0')
          {
              if(*str++ == '\n')
              linenum++;
          }
          return linenum;
      
      }
      • 单词统计函数
      /*
      **单词统计
      */
      int Wordnum(char* str)
      {
          char*  currpt;
          int count=0;
          while(*str != '\0')
           {
               if(!(((*str>=0x41)&&(*str<=0x5A))||((*str>=0x61)&&(*str<=0x7A))))
               {
                  str++;
                  continue;
              }
              else
              {
                  currpt = str+1;
                  do
                  {
                      if(!(((*currpt>=0x41)&&(*currpt<=0x5A))||((*currpt>=0x61)&&(*currpt<=0x7A))))
                      {
                          count++;
                          str = currpt;
                          break;
                      }
                  }while(*(++currpt) != '\0');
              }
      
      
          }
          return count;
      
      }
    • 将结果写入文件
    /*
    **结果输出
    */
    fpwrite = fopen(outputfile,"w+");
    fwrite(outstr,sizeof(char),strlen(outstr),fpwrite);
    fclose(fpwrite);

转载于:https://www.cnblogs.com/HuppertWu/p/9728133.html

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值