C语言查找字符串在文件中的第几行第几列

面试中遇到的问题,回来后当做练习写了一下,巩固一下知识。
现将代码贴出来:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int search_str(const char*p_str,int *row,int *col,FILE*fp){
    char line[512] = {0};
    char *p = NULL;
    int i = 0;
    while(fgets(line,512,fp)){
        i ++;
        p = strstr(line,p_str);
        if(p){
            *row = i;
            *col = p - line+1;
            return 1;
        }
    }
    return 0;
}

int main(){
   int row,col;
   int get;  //查找结果
   //从test.txt中查找
   FILE *fp =  fopen("./test.txt","r+");
   if(NULL == fp){
       printf("Error open file\n");
       exit(0);
   }

   got = search_str("hello",&row,&col,fp);
   if(got){
      printf("hello is at row %d col %d\n",row,col);
   }
   else {
      printf("not find\n");
   }
   fclose(fp);
   return 0;
}

现在编译:

$ gcc test.c
$ 

创建一个文件test.txt,内容如下:

It is a test line
It is a test line
It is a test line
It is a test line
It is a test line
ok,'hello' is here

现在运行程序:

$ ./a.out
hello is at row 6 col 5
$ 
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值