• C examples


    最近在看David R. Hanson 的《C Interfaces and Implementations》,文中第一章提到了Literate Programming

    作者举了一个例子: 

    功能:用于检测输入中相邻且相同的单词

    #include<stdio.h>
    #include<math.h>
    #include<errno.h>
    #include<stdlib.h>
    #include<ctype.h>
    #include<string.h>
    
    int linenum;
    
    int getword(FILE *,char *,int);
    void doubleword(char *,FILE *);
    
    int main(int argc,char *argv[]){
    
      int i;
      for(i=1; i<argc; i++){
        FILE *fp=fopen(argv[i],"r");
        if(fp==NULL){
          fprintf(stderr,"%s: can't open '%s'(%s)\n",argv[0],argv[i],strerror(errno));
          return EXIT_FAILURE;
        }else{
           doubleword(argv[i],fp);
           fclose(fp);
        }
      }
      if(argc==1) doubleword(NULL,stdin);
      return EXIT_SUCCESS;
    }
    
    int getword(FILE *fp, char *buf, int size){
    
      int c;
      c=getc(fp);
      for(; c!=EOF && isspace(c); c=getc(fp)) //scan forword to a nonspace character or EOF
        if(c=='\n')
          linenum++;
        else{                //copy the word into buf[0……size-1]
          int i=0;
          for(: c!=EOF && !isspace(c); c=getc(fp))
            if(i<size-1)    //size means the max length of any word int the text
              buf[i++]=tolower(c);
          if(i<size)
            buf[i]='\0';
        }
    
      if(c!=EOF)
        ungetc(c,fp);
      return buf[0]!='\0';
    
    }
    
    void doubleword(char *name,FILE *fp){
       char prev[128],word[128];
       linenum=1;
       prev[0]='\0';
       while(getword(fp,word,sizeof(word))){
          if(isalpha(word[0])&& strcmp(prev,wortd)==0){
              if(name)
                printf("%s:",name);
              printf("%d:%s\n",linenum,word);
    
           }
    
        }
    }
    

  • 相关阅读:
    Basic Calculator II
    理解与模拟一个简单servlet容器
    括号字符串有效性验证
    理解与模拟一个简单web服务器
    Tomcat日志输出在linux和windows差异
    SqlCommand执行带GO的SQL脚本文件
    《第一行代码》添加百分比布局库依赖问题
    final 和 static之间的区别和联系
    oracle DB 使用注意点小结
    方法重载(method overloading)
  • 原文地址:https://www.cnblogs.com/cpoint/p/2070199.html
Copyright © 2020-2023  润新知