Search code examples
cformattingprintf

Retain formatting in printf with %s


So I have a string char *str = someString(); and I want to print the string and retain any formatting that may be present in the string with printf("%s", str); So for instance, if str were equal to "\033[32mPassed!\n\033[0m", I would want it to print Passed! in green followed by a new line. But currently, it prints the string literally. Is this something printf can do or is it not designed for this? I understand that this could cause issues if the string contained something like %d without actually having a number passed.


Solution

  • Sending ␛[32mPassed!␊␛[0m to the terminal is what causes the desired effect.[1]

    You are asking how convert the string "\033[32mPassed!\n\033[0m" into the string ␛[32mPassed!␊␛[0m, just like the C compiler does when provided the C code (C string literal) "\033[32mPassed!\n\033[0m".

    printf does not provide a way to convert a C string literal into the string it would produce.

    And nothing else in the standard library does either. The functionality of parsing C code is entirely located in the compiler, not in the executable it produces.

    You will need to write your own parser. At the very least, you will need to do the following:

    1. Remove the leading and trailing quotes.
    2. Replace the four character sequence \033 with character 0x1B.
    3. Replace the two character sequence \n with character 0x0A.

    Footnotes

    1. Assuming the terminal understands these ANSI escape sequences.