C++ finds the location of a word in the text

  • 2020-05-09 18:54:47
  • OfStack

The code is very simple, the function is also very single 1, here is no more nonsense, you directly look at the code.


#include <stdio.h>
#include <string.h>
 
int main(int argc,char**argv){
  char *token = argv[1];
  FILE *fp = fopen("./test.txt","a+");
  char buf[1024];
  char *p;
  int s=-1,len=strlen(token),line=0,pos=-1;
 
  while(!feof(fp)){
    fgets(buf,sizeof(buf),fp);
    line ++;  
    p = buf;
    while(*p){
      if(*p==token[0] && s==-1){
        s = 0;
      }else if(*p==token[s+1]){
        s ++;
      }else{
        s = -1;
      }
 
      p++;
      if(s==len-1){
        printf("(%d,%d)\n",line,p-buf-len+1);
        s=-1;
      }
    }
    s=-1;
  }
}


Related articles: