#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct st_result{
char caStr[ 100 ];
struct st_result *next;
};
int fetch_string( char *cpPath, struct st_result **stpResult);
int clear_result( struct st_result *stpResult);
int
main( int argc, char *argv[] )
{
struct st_result *stpResult = NULL;
int iRet = 0;
if( argc != 2 )
{
fprintf( stderr, "usage: %s file\n", argv[ 0 ] );
return -1;
}
iRet = fetch_string( argv[ 1 ], &stpResult );
if( iRet == 0 )
{
struct st_result *stpTmp = stpResult;
while( stpTmp != NULL )
{
printf( "str: %s\n", stpTmp->caStr );
stpTmp = stpTmp->next;
}
}
clear_result( stpResult );
return iRet;
}
int
fetch_string( char *cpPath, struct st_result **stpResult )
{
FILE *fp = NULL;
char caPreLine[ 512 ];
char caCurLine[ 512];
char caPreStd[ 128 ];
char caEndStd[ 128 ];
char caStrStd1[ 512 ];
char caStrStd2[ 512 ];
if( ( fp = fopen( cpPath, "r" ) ) == NULL )
{
fprintf( stderr, "fopen error\n" );
return -1;
}
while( fgets( caCurLine, 512, fp ) != NULL )
{
struct st_result *stpTmp = NULL;
char *cpTmp = NULL;
if( caCurLine[ strlen( caCurLine ) - 1 ] == '\n' )
caCurLine[ strlen( caCurLine ) - 1 ] = '\0';
if( strstr( caCurLine, "hello" ) == NULL )
{ /* not find the 'hello' */
strcpy( caPreLine, caCurLine );
continue;
}
/* find the hello */
if( ( stpTmp = malloc( sizeof( struct st_result ) ) ) == NULL )
{
fprintf( stderr, "malloc error\n" );
return -1;
}
stpTmp->next = *stpResult;
*stpResult = stpTmp;
sscanf( caCurLine, "%s", stpTmp->caStr );
sscanf( caPreLine, "%[^-]", caPreStd );
if( ( cpTmp = strstr( caPreLine, "->" ) ) != NULL )
{
strcpy( caEndStd, cpTmp + strlen( "->" ) );
}
strcpy( caStrStd1, caPreLine );
sprintf( caStrStd2, "%s->%s", caEndStd, caPreStd );
break;
}
memset( caPreLine, 0x0, sizeof( caPreLine ) );
while( fgets( caCurLine, 512, fp ) != NULL )
{
struct st_result *stpTmp = NULL;
if( caCurLine[ strlen( caCurLine ) - 1 ] == '\n' )
caCurLine[ strlen( caCurLine ) - 1 ] = '\0';
/* if previous line is A->B or B->A */
if( strstr( caPreLine, caStrStd1 ) != NULL || strstr( caPreLine, caStrStd2 ) != NULL )
{
if( ( stpTmp = malloc( sizeof( struct st_result ) ) ) == NULL )
{
clear_result( *stpResult );
fprintf( stderr, "malloc error\n" );
return -1;
}
stpTmp->next = *stpResult;
*stpResult = stpTmp;
sscanf( caCurLine, "%s", stpTmp->caStr );
strcpy( caPreLine, caCurLine );
}
else
strcpy( caPreLine, caCurLine );
}
return 0;
}
int
clear_result( struct st_result *stpResult)
{
while( stpResult != NULL )
{
struct st_result *stpTmp = stpResult;
stpResult = stpResult->next;
free( stpTmp );
}
return 0;
}