C語言查找字符串在文件中的第幾行第幾列

面試中遇到的問題,回來後當做練習寫了一下,鞏固一下知識。
現將代碼貼出來:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int search_str(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);
   }

   get = search_str("hello",&row,&col,fp);
   if(get){
      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
$ 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章