fork download
  1.  
  2. #define _GNU_SOURCE
  3.  
  4. #include <stdlib.h>
  5. #include <stdio.h>
  6. #include <string.h>
  7.  
  8. char *data = "cs\n"
  9. "cs hello there\n"
  10. "hello there cs\n"
  11. "cs\n"
  12. "hello there cscs there cs.\n"
  13. "cs cs cs\n"
  14. "test\n";
  15.  
  16. int main(void)
  17. {
  18. char *remove = "cs"; // word that needs to be removed
  19. char word[50]; // word that is being checked
  20. char space;
  21.  
  22. int nwords = 0; // total no. of words in input
  23. int nremoved = 0; // no. of removals
  24. int nwritten = 0; // no. of words on this line
  25.  
  26. // treat dada above as file
  27.  
  28. FILE *f = fmemopen(data, strlen(data), "r");
  29.  
  30. // dump original text
  31.  
  32. printf("%s--\n", data);
  33.  
  34. while (fscanf(f, "%49s", word) == 1) {
  35. int cmp = strcmp(word, remove);
  36.  
  37. // print or skip word;
  38.  
  39. if (cmp == 0){
  40. nremoved++;
  41. } else {
  42. printf("%s", word);
  43. nwritten++;
  44. }
  45.  
  46. // treat white space / newline
  47.  
  48. if (fscanf(f, "%c", &space) != 1) space = '\n';
  49.  
  50. if (space == '\n') {
  51. if (nwritten) putchar(space);
  52. nwritten = 0;
  53. } else {
  54. if (cmp) putchar(space);
  55. }
  56.  
  57. nwords++;
  58. }
  59.  
  60. printf("--\n%d words read\n%d words removed\n", nwords, nremoved);
  61.  
  62. fclose(f);
  63.  
  64. return 0;
  65. }
  66.  
Success #stdin #stdout 0s 5544KB
stdin
Standard input is empty
stdout
cs
cs hello there
hello there cs
cs
hello there cscs there cs.
cs cs cs
test
--
hello there
hello there 
hello there cscs there cs.
test
--
17 words read
7 words removed