用c语言写一个接口函数,能够搜索txt文件的内容
时间: 2023-12-10 16:41:51 浏览: 29
以下是一个简单的C语言函数,可以搜索一个txt文件中的内容并返回匹配的行数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int search_txt(const char *filename, const char *query) {
FILE *fp;
char *line = NULL;
size_t len = 0;
ssize_t read;
int line_num = 0;
int matches = 0;
fp = fopen(filename, "r");
if (fp == NULL) {
printf("Error opening file %s\n", filename);
return -1;
}
while ((read = getline(&line, &len, fp)) != -1) {
line_num++;
if (strstr(line, query) != NULL) {
printf("Match found in line %d: %s", line_num, line);
matches++;
}
}
fclose(fp);
if (line) {
free(line);
}
return matches;
}
```
调用该函数的方式如下:
```c
int num_matches = search_txt("example.txt", "search query");
printf("Found %d matches", num_matches);
```
其中,第一个参数是要搜索的文件名,第二个参数是要搜索的查询字符串。函数返回的是找到的匹配行数。