统计文本文件字符(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);
    • 实例展示


    • 全部代码展示

猜你喜欢

转载自www.cnblogs.com/HuppertWu/p/9728133.html