Search code examples
cfile-management

How to remove a word from text file in C program?


So I have a file called test.txt with the following text:

Hello World! I hope you are doing well. I am also well. Bye see you!

Now I want to remove the word Bye from the text file. I want to make changes in the same file, in the test.txt file, not in a seperate file. How do I do that in C program?

Thanks in advance


Solution

  • This example worked for phrases, I didn't check for larger files or with more content.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void remove_word(char * text, char * word);
    
    int main()
    {
        char * filename     = "test.txt";
        char * text         = (char*)malloc(sizeof(char) * 100);
        char * wordToRemove = (char*)malloc(sizeof(char) * 20);
        // Word to remove
        strcpy(wordToRemove, "Bye"); 
        
        // Open for both reading and writing in binary mode - if exists overwritten
        FILE *fp = fopen(filename, "wb+");
        if (fp == NULL) {
            printf("Error opening the file %s", filename);
            return -1;
        }
        // Read the file
        fread(text, sizeof(char), 100, fp);
        printf ("Readed text: '%s'\n", text);
    
        // Call the function to remove the word
        remove_word(text, wordToRemove);
        printf ("New text: '%s'\n", text);
    
        // Write the new text
        fprintf(fp, text);
        fclose(fp);
    
        return 0;
    }
    
    void remove_word(char * text, char * word)
    {
        int sizeText = strlen(text);
        int sizeWord = strlen(word);
        
        // Pointer to beginning of the word
        char * ptr = strstr(text, word);
        if(ptr)
        {
            //The position of the original text
            int pos = (ptr - text);
    
            // Increment the pointer to go in the end of the word to remove
            ptr = ptr + sizeWord;                
            
            // Search in the phrase and copy char per char
            int i;
            for(i = 0; i < strlen(ptr); i++)
            {
                text[pos + i] = ptr[i]; 
            }
            // Set the "new end" of the text               
            text[pos + i] = 0x00;      
        }   
    }