面试中遇到的问题,回来后当做练习写了一下,巩固一下知识。
现将代码贴出来:
#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
$