c语言查找文件中的字符串
时间: 2023-06-23 13:48:07 浏览: 244
在 C 语言中,可以使用标准库函数 `fgets()` 和 `strstr()` 来查找文件中的字符串。具体步骤如下:
1. 打开文件,可以使用 `fopen()` 函数。
2. 使用 `fgets()` 函数逐行读取文件内容,将读取到的每行文本保存到一个缓冲区中。
3. 使用 `strstr()` 函数在缓冲区中查找目标字符串。如果找到了,就可以对其进行相应的处理。
4. 重复步骤 2 和 3,直到文件读取完毕。
以下是一个示例代码,用于在文件中查找指定的字符串:
```c
#include <stdio.h>
#include <string.h>
int main() {
FILE* fp;
char buf[1024];
fp = fopen("test.txt", "r");
if (fp == NULL) {
printf("Failed to open file.\n");
return -1;
}
while (fgets(buf, sizeof(buf), fp) != NULL) {
if (strstr(buf, "target string") != NULL) {
printf("Found the target string: %s\n", buf);
}
}
fclose(fp);
return 0;
}
```
其中,`test.txt` 是要查找的文件名,`target string` 是要查找的目标字符串。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)