/*
replace.c

Replaces the first occurence of the search string with
the replace string for each line of input.  The search
string and replacement string are given as arguments
on the command line.

This program is a simple demonstration of string handling
in C.  Note that we avoid the use of:

  o  strncpy(), because it doesn't null-terminate the string
     after copying for us,
  o  gets(), because it doesn't allow us to limit the input
     to the maximum length of the string,
  o  puts(), because it adds a newline to our string.

Note that if the string resulting from a replacement is too 
long, a buffer overflow may occur.

Ray Ontko 1999/11/17
*/

#include <stdio.h>
#include <string.h>

#define MAX_LINE 100

int main( int argc , char *argv[] )
{
  char *search_string ;
  char *replace_string ;
  char *pos ;
  char s[MAX_LINE] ;
  char t[MAX_LINE] ;

  if( argc != 3 )
  {
    printf( "usage: %s search-string replace-string\n" , argv[0] ) ;
    return 1 ;
  }
  
  search_string = argv[1] ;
  replace_string = argv[2] ;

  while( fgets( s , MAX_LINE , stdin ) != NULL )
  {
    if( ( pos = strstr( s , search_string ) ) != NULL )
    {
      t[0] = '\0' ;
      strncat( t , s , pos - s ) ;
      strcat( t , replace_string ) ;
      strcat( t , pos + strlen( search_string ) ) ;
      strcpy( s , t ) ;
    }
    fputs( s , stdout ) ;
  }

  return 0 ;
}
