Gaarsin
Gaarsin

Reputation: 33

Reading file character-by-character and comparing those characters in C

I've got a little program that reads through a text file character-by-character and checks if the file contains certain values.

If it finds the letter A next to another letter I want the file to push the second letter to a new line and print the result. For example, if I had the following text file:

ABABAAAB

The printed result would be:

A
B
A
B
A
A
A
B

Would I need to store the current character being read in a variable say called "prevChar" then record the next character in a variable called "currentChar" then compare them and print the result? Keep doing this for every character?

Upvotes: 0

Views: 1101

Answers (1)

Dejan Dimčić
Dejan Dimčić

Reputation: 294

You can do this with one bool variable, say boolean newLine = false;, initialized to false. That will be indicator that let you know if last character was A.

 boolean newLine = false;
    FILE *fp;
    int c;

    fp = fopen("datafile.txt", "w");

    while((c = fgetc(fp)) != EOF) {
        if (newLine) {
            // Here you put char in new line
            if (c == 'A'){
                newLine = true;
            }
            else {
                newLine = false;
            }
        }
    }

    fclose(fp);

Upvotes: 1

Related Questions