Developer87
Developer87

Reputation: 2708

Replace characters in a file

I need to replace every alphabetical character with a specific one in my file.txt. I wrote following code snippet:

FILE *file;
char c;
file = fopen(filename, "r+");

char chars[] = { 'a', 'b', 'c', 'd', 'e', 
                 'f', 'g', 'k', 'l', 'm',
                 'n', 'o', 'p', 'r', 's', 
                 't', 'u', 'v', 'w', 'x', 
                 'y', 'z'};
    while ((c = getc(file)) != EOF) {
        if (c == 'd') {
            continue;
        }
        if (strchr(chars, c) != NULL) {
            fseek(file, 0, SEEK_CUR);
            fputc((int)specific_char, file);
            fflush(file);
        }
    }
    fclose(file);
}

But for some reason it replaces all the characters from my file. But I need to replace all except 'd'.

What's the problem with my code? (Code should be written in C, not in C++)

Thanks to everyone.

Upvotes: 0

Views: 2677

Answers (1)

selbie
selbie

Reputation: 104514

Several bugs I see:

For starters, you should have a null char on your "chars" array such that the strchr call works as expected:

char chars[] = { 'a', 'b', 'c', 'd', 'e', 
                 'f', 'g', 'k', 'l', 'm',
                 'n', 'o', 'p', 'r', 's', 
                 't', 'u', 'v', 'w', 'x', 
                 'y', 'z', '\0'};

You could just as easily replace the above array with a string declaration. And you don't need an explicit null char since it's implicitly part of the string literal.

char* chars= "abcdefghijklmnopqrstuvwxyz";

Also, this statement:

fseek(file, 0, SEEK_CUR);

is a no-op and doesn't do anything. I think you want to set the file pointer backwards by one char. Hence, this is what you want:

fseek(file, -1, SEEK_CUR);

The fflush call is not needed and will only hinder performance. Might be useful for debugging, but you probably don't need it.

Upvotes: 2

Related Questions