Home > Back-end >  How to replace a character in text file using C?
How to replace a character in text file using C?

Time:12-02

I need to read a text file (E3-5.txt), and search for character c1 to be replaced by c2. This is my incomplete code:

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

int main()
{
    char c;
    char c1 = 'm';
    char c2 = 'a';
    int i;
    FILE* fp;
    fp = fopen("C:\\E3-5.txt", "r ");
    if (fp == NULL)
    {
        printf("File not found!");
        return 0;
    }
    for(c = getc(fp); c != EOF; c = getc(fp))
    {
        if(c == 'm')
        {
            i = ftell(fp);
            printf("\nPosition %d", i);
        }

    }
}

I am having trouble how to locate the position of c1 in the text and how to rewrite it.

CodePudding user response:

Here you have a very naive one:

int freplace(FILE *f, char needle, char repl)
{
    int result = 1;
    int c;
    if(f)
    {
        while((c = fgetc(f)) != EOF)
        {
            if(c == needle)
            {
                fseek(f, -1, SEEK_CUR);
                fputc(repl, f);
                //all I/O functions require error handling
            }
        }
    }
    return result;
}

CodePudding user response:

getc() returns an int so you need to declare int c not char c to check for the EOF.

ftell() gets the location. Use fwrite() or fputc() to write to file at that location by setting with fseek().

Go to https://en.cppreference.com/w/c for reference. Lots of beginners fail to read all of the standard library functions, and some even reinvent the wheel.

  • Related