zoukankan      html  css  js  c++  java
  • 统计文本文件字符(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++ != '')
            {
                totalchar++;
            }
            return totalchar;
        
        }
        
        • 文本行处理函数
        /*
        **行数统计
        */
        int Linenum(char* str)
        {
            int linenum = 0;
            while(*str != '')
            {
                if(*str++ == '
        ')
                linenum++;
            }
            return linenum;
        
        }
        
        • 单词统计函数
        /*
        **单词统计
        */
        int Wordnum(char* str)
        {
            char*  currpt;
            int count=0;
            while(*str != '')
             {
                 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) != '');
                }
        
        
            }
            return count;
        
        }
        
      • 将结果写入文件

      /*
      **结果输出
      */
      fpwrite = fopen(outputfile,"w+");
      fwrite(outstr,sizeof(char),strlen(outstr),fpwrite);
      fclose(fpwrite);
      
  • 相关阅读:
    第11周学习进度条
    人月神话阅读笔记03
    人月神话阅读笔记02
    第10周学习进度条
    对各团队的评价意见
    第九周学习进度条
    《构建之法阅读笔记05》
    站立会议10
    第十一周学习进度
    cnblogs.com的用户体验
  • 原文地址:https://www.cnblogs.com/HuppertWu/p/9728133.html
Copyright © 2011-2022 走看看