#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”
。
我无法打印包含搜索词的行。我正在尝试使用指针移动到当前行的开头,然后逐步导航,但我有点卡在如何让指针停在行尾并打印到那一点。
最佳答案
您的代码的问题是,您在代码中调用了 free(bytes);
,然后您继续使用 bytes
。这会调用 undefined behavior .
另外,我会建议
更改您的
scanf()
指令scanf("%s", file_name);
和
scanf("%s", search);
到
scanf("99%s", file_name);
和
scanf("9%s", search);
避免缓冲区溢出的风险。
在使用返回的指针之前始终检查
fopen()
是否成功。
不过,从逻辑上来说,我还是建议你
注意事项:
main()
的推荐签名是int main(void)
。- 始终初始化所有 局部变量。
关于c - 打印从包含特定单词的文件中读取的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30149136/