#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define _MAXSTRING_ 100
struct FileSearch
{
int Search( FILE *f, char *string );
int FindLen( FILE *g, int currentpos );
void PrintLines( FILE *fp, int pos );
};
FileSearch acc;
void main()
{
FILE *file;
char *filename = "your filename";
char *string = "the string that need to be search";
int pos;
file = fopen( filename, "r" );
if(!file)
{
fprintf( stderr,"There was an error while opening \"%s\".\n",filename);
exit(1);
}
if(( pos = acc.Search( file, string )) != -1 )
{
acc.PrintLines( file, pos );
while(( pos = acc.Search( file, string )) != -1 )
{
acc.PrintLines( file, pos );
}
}
else
{
printf("Can't find the string \"%s\"\n",string);
}
fclose(file);
}
// search for a specific string in a file
int FileSearch::Search( FILE *f, char *string )
{
char *sentence;
bool found = false;
char *pdest;
int pos;
sentence = (char*)malloc( sizeof(char) * _MAXSTRING_ );
if( !sentence )
{
fputs("memory allocation has fail.\n", stderr );
exit(1);
}
while( fgets( sentence, _MAXSTRING_, f ) != NULL )
{
if((pdest = strstr( sentence, string )) != NULL )
{
found = true;
break;
}
}
if(found)
{
pos = pdest - sentence;
delete sentence;
return pos;
}
free(sentence);
return -1;
}
// find the lengh of the current line
int FileSearch::FindLen( FILE *g, int currentpos )
{
char c;
int len = 0;
rewind(g);
while(( c = getc(g)) && ftell(g) != currentpos && !(feof(g)))
{
len++;
if( c == '\n' )
len = 0;
}
return len;
}
void FileSearch::PrintLines( FILE *fp, int pos )
{
char c;
int line = 0;
int count = 0;
int len = FindLen( fp, ftell(fp));
fseek( fp, -(len + 2), 1 ); // place the file pointer to the begining of the current line
while(( c = getc(fp)) && line != 16 && !(feof(fp)))
{
if( c == '\n' )
line++;
count++; /* count the characters */
putchar(c);
}
fseek( fp, len - ( count + pos ), 1 );
printf("\n\n /***********************************************/\n");
}