How to remove all occurrences of a word from text file in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void removeWord(char *s, char word[]) {
	 char *p = s;
	 while( (p = strstr(p, word)) ) {
		 int word_index = p - s; 
		 for (int j = word_index, i = word_index + strlen(word) + 1; i < strlen(s); i++, j++) {
		  	  s[j] = s[i];
		 }
		 s[strlen(s) - strlen(word)] = '\0';
		p++;
	 }
	 s[strlen(s) - strlen(word)] = '\0';
}

void readFile(char file[]) {
    FILE *fp = fopen(file, "r");
        
    char ch;
    while ((ch = fgetc(fp)) != EOF)
        putchar(ch);
 
    fclose(fp);
}
   
int main()
{
    char file[100] = "d:\\data.txt";
    char filetmp[100] = "d:\\tmp.txt";
	char word[10] = "is";
	
    FILE *fp = fopen(file, "r");  
    FILE *fptmp = fopen(filetmp, "w");  

    if (fp == NULL || fptmp == NULL) {
        printf("Error open file\n");
        exit(EXIT_FAILURE);
    }
   
	readFile(file);
	
	char s[100];
	while ((fgets(s, 100, fp)) != NULL) {
        removeWord(s, word);
        fputs(strcat(s, "\n"), fptmp);
    }

    fclose(fp);
    fclose(fptmp);

    remove(file);
    rename(filetmp, file);
	
	puts("\n");
    readFile(file);

    return 0;
}
    
      
      
      
/*
run:
      
c is c++ c# is
java is python
is javascript is php

c c++ c#
java python
javascript php
   
*/

 



answered Jul 8, 2020 by avibootz

Related questions

1 answer 147 views
1 answer 53 views
1 answer 144 views
1 answer 151 views
1 answer 145 views
1 answer 133 views
...