Replace placeholders with text - C?

2019-07-16 14:59发布

问题:

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:

you could also take a more primitive approach also by reading it in 1 character at a time and then breaking out if char=='!' and then build a string up til the other '!' and then just compare that string with your list of replacements..

@goe's reply To say push a char.. here is some code


//c is char read from file
if(c=='!'){
  char str[100];
  c=fgetc
  int i=0;
  while(c!='!'){
    str[i]=c;
    i++;
    c=fgetc
  }
  i++;
  str[i]='\0'; //null terminate
  if(strcmp(str,"....")... //continue... 
}



回答2:

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.



回答3:

Construct a finite automaton aka state machine?



回答4:

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



标签: c replace