使用C++的find()函数,实现从一个文件中查找一个字符串的程序
时间: 2024-05-01 16:16:57 浏览: 68
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 100
int main() {
char filename[MAX_LEN], search_str[MAX_LEN];
printf("Enter filename: ");
scanf("%s", filename);
printf("Enter string to search: ");
scanf("%s", search_str);
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("Failed to open file.\n");
return 1;
}
char line[MAX_LEN];
int line_num = 1, found = 0;
while (fgets(line, MAX_LEN, fp) != NULL) {
char *pos = strstr(line, search_str);
if (pos != NULL) {
printf("Found \"%s\" in line %d: %s", search_str, line_num, line);
found = 1;
}
line_num++;
}
if (!found) {
printf("String \"%s\" not found in file.\n", search_str);
}
fclose(fp);
return 0;
}
```
阅读全文