首页 > 技术文章 > 访问txt文本文件查找特定字符串,找到所有字符串的首地址

victorywr 2020-08-14 17:11 原文

#include <stdio.h>
#include <string.h>
 
int main(){
	
  char *token = "she";
  FILE *fp = fopen("test.txt","a+");
  char buf[1024];
  char *p;
  int s=-1,len=strlen(token),line=0;
 
  while(!feof(fp)){                 //feof()是文件结束检测函数,若结束了返回1,否则为0 
    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统计当前满足符合查找字符的位置,一旦查找完一个字符,立马让s=-1,进行下一轮查找 
        s ++;
      }else{
        s = -1;
      }
 
      p++;
      if(s==len-1){
        printf("(%d,%d)\n",line,p-buf-len+1);   //(p-buf)是指针p相对于buf首地址的偏移量,要确定查询字符首部的位置,还需要减去字符长度
        //s=-1;
      }
    }
    s=-1;
  }
}

 test.txt内容如下:

 

运行结果:

 

推荐阅读