tags:

views:

185

answers:

4

I use the below function to retrieve characters one by one from a FILE stream. Now the text in that file will sometimes include places holders like !first_name! within the text. What's the best way to detect when such a place holder start and when it ends so that I can swap each character between !! with proper character from another storage?

void print_chars(FILE *file) {
        fseek(file, 0L, 0);
        int cr;

        do {
              cr = fgetc(file);
              putchar(cr);
        } while (cr != EOF);
}
+1  A: 

Construct a finite automaton aka state machine?

Dmitry
This is a good answer too. Reminds me of my Compiler homework using finite automata.
Mithrax
I would say its a bit overkill though for something simple like this
Earlz
+5  A: 

Start by using fgets() to read lines at a time, and then (assuming placeholders won't have spaces or newlines in them), use strchr() to locate the first exclamation mark, another to find the second, and strcpsn() or strspn() to ensure that only permitted characters appear between them. Then write what goes before the first exclamation mark and the replacement text, and then resume scanning for more placeholders on the same line.

Jonathan Leffler
I was going to write this answer up eventually. And then I didn't. +1 I would have tried to work within his char-at-a-time framework, but this is probably easier.
Chris Lutz
+1  A: 
Earlz
That's what I think I'll do. Could you tell me how I can push if you will a single char into a char some_string[100]; ? Is there a good function that would allow me to do that?
goe
I edited my answer to give that
Earlz
+1  A: 

If you want something reliable that handles corner cases, consider using a real lexical analysis tool like Lex or re2c.

Eli Bendersky