fork(8) download
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4.  
  5. int main()
  6. {
  7. FILE *input = stdin;
  8. FILE *output = stdout;
  9.  
  10. char buffer[512];
  11. while (fgets(buffer, sizeof(buffer), input) != NULL)
  12. {
  13. /* The text to find */
  14. static const char text_to_find[] = "xyz";
  15.  
  16. /* The text to replace it with */
  17. static const char text_to_replace[] = "abc";
  18.  
  19. char *pos = strstr(buffer, text_to_find);
  20. if (pos != NULL)
  21. {
  22. /* Allocate memory for temporary buffer */
  23. char *temp = calloc(
  24. strlen(buffer) - strlen(text_to_find) + strlen(text_to_replace) + 1, 1);
  25.  
  26. /* Copy the text before the text to replace */
  27. memcpy(temp, buffer, pos - buffer);
  28.  
  29. /* Copy in the replacement text */
  30. memcpy(temp + (pos - buffer), text_to_replace, strlen(text_to_replace));
  31.  
  32. /* Copy the remaining text from after the replace text */
  33. memcpy(temp + (pos - buffer) + strlen(text_to_replace),
  34. pos + strlen(text_to_find),
  35. 1 + strlen(buffer) - ((pos - buffer) + strlen(text_to_find)));
  36.  
  37. fputs(temp, output);
  38.  
  39. free(temp);
  40. }
  41. else
  42. fputs(buffer, output);
  43. }
  44.  
  45. return 0;
  46. }
  47.  
Success #stdin #stdout 0.01s 1856KB
stdin
1 xyz 23
2 xyz 45
stdout
1 abc 23
2 abc 45