/* Search.c (c) Kari Laitinen http://www.naturalprogramming.com 1997-??-?? File created. 2013-11-19 Last modification. */ #include #include #include void search_string_in_file( char file_name_from_caller[], char string_to_be_searched[] ) { FILE *file_pointer ; char text_line_from_file[100] ; int line_counter = 0 ; file_pointer = fopen( file_name_from_caller, "r" ) ; if ( file_pointer == NULL ) { printf( "\n Error in opening file %s !\n", file_name_from_caller ) ; } else { printf ( "\n Searching.. \"%s\"\n", string_to_be_searched ) ; while( fgets( text_line_from_file, sizeof ( text_line_from_file ), file_pointer ) != 0 ) { line_counter ++ ; if ( strstr( text_line_from_file, string_to_be_searched ) != 0 ) { printf( "\nString \"%s\" ", string_to_be_searched ) ; printf( "was found on line %d", line_counter ) ; } } fclose( file_pointer ) ; } } int main( int number_of_command_line_arguments, char* command_line_arguments[] ) { char file_name_given_by_user[ 20 ] ; char string_to_be_searched[ 100 ] ; if ( number_of_command_line_arguments == 3 ) { search_string_in_file ( command_line_arguments[ 1 ], command_line_arguments[ 2 ] ) ; } else { printf( "\n This program can search a string in a " ) ; printf( "\n text file. Give first a file name : " ) ; gets( file_name_given_by_user ) ; printf( "\n Type in a string to be searched: " ) ; gets( string_to_be_searched ) ; search_string_in_file( file_name_given_by_user, string_to_be_searched ) ; } }