2

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

Subreena
  • 158
  • 1
  • 1
  • 10
  • You cannot directly delete a byte from a file in C, you'll have to read the file in an array or any other data structure, and delete accordingly from there and write it back to the file. – JASLP doesn't support the IES Jun 22 '21 at 17:15
  • You also need to truncate the file if your resulting data is shorter than before the changes https://stackoverflow.com/questions/873454/how-to-truncate-a-file-in-c – Sven Nilsson Jun 22 '21 at 17:38
  • @Subreena https://codeforwin.org/2018/02/c-program-remove-word-from-file.html Follow this process. – Pritom Sarkar Jun 22 '21 at 17:40

1 Answers1

3

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;      
    }   
}
Arcaniaco
  • 400
  • 2
  • 10