#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i, p=0;;
int c;
char file_name[100];
char search[10];
printf("Enter the file name:");
scanf("%s", file_name);
printf("Search word:");
scanf("%s", search);
FILE *f = fopen((strcat(file_name, ".txt")), "rb");
fseek(f, 0, SEEK_END);
long pos = ftell(f);
fseek(f, 0, SEEK_SET);
char *bytes = malloc(pos + 1);
fread(bytes, pos, 1, f);
bytes[ pos ] = '\0';
/*search*/
if (strstr(bytes, search) != NULL){
printf("found\n");
p = 1;}
else{
printf("Not found\n");
p=0;}
free(bytes);
char *found = strstr( bytes, search );
if ( found != NULL )
{
char *lineStart;
for(lineStart = strchr(bytes, '\n'); !strcmp(lineStart,"\n");
lineStart = strchr(lineStart+1, '\n')){
printf("%s\n", lineStart);
}
}
}
上述代码应该在文件(.txt)
中搜索一个单词,如果找到它应该打印"found"
并打印它找到的行。例如,如果搜索一个单词"Brick"
在文件中,如果在"The house is made of red bricks"
这样的句子中找到,则将整个句子打印为输出即"The house is made of the red bricks"
。
我在打印包含搜索词的行时遇到问题。我试图使用指针移动到当前行的开头,然后逐步导航,但我有点陷入如何使指针停在行尾,只是打印到那一点。