【发布时间】:2015-07-20 20:43:21
【问题描述】:
#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移动到您不再需要它的位置,例如。最后 -
@Hi-Angel 好吧,你可以。 :-)
c99以后。 -
@Hi-Angel 恕我直言,您可以删除评论。不知何故,这是一种误导。希望你能理解。 :-)
标签: c pointers file-io printf free