Reputation: 602
#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);
}
}
}
The above stated code is supposed to search for a word in a file (.txt)
and if found it should print "found"
and print the line it was found in. For example, if searched for a word "Brick"
in the file, and if found in a sentence like "The house is made of red bricks"
, then it prints the whole sentence as the output i.e "The house is made of the red bricks"
.
I am having trouble printing the line containing the search word. I am trying to use pointer to move to the start of the current line and then navigate incrementally but I am kinda stuck in how to make the pointer stop at the end of the line and just print up till that point.
Upvotes: 1
Views: 2183
Reputation: 134376
The issue with your code is, you call free(bytes);
inside your code and after that, you continue to use bytes
. This invokes undefined behavior.
Also, i'll suggest
change your scanf()
instruction
scanf("%s", file_name);
and
scanf("%s", search);
to
scanf("99%s", file_name);
and
scanf("9%s", search);
to avoid the risk of buffer overflow.
Always check for the success of fopen()
before using the returned pointer.
However, from the logical point, i'll suggest you
fgets()
strstr()
.fgets()
return NULL.Notes:
main()
is int main(void)
.Upvotes: 4