Search code examples
cprintfasciioctal

Print string with ASCII in octal notation in C


I open a file, get its contents, look for matches for a regex pattern and print the matches out one by one. Some of the matches contain octal notation eg. \012 for newlines.

When I simply apply printf("%s\n", match); it gets printed out as \012. Is there a way to print out the respective ASCII characters instead (a newline in this case)?


Solution

  • If match is a string, you can use the function strtol in <stdlib.h> to convert it to an int by specifying base 8:

    int num = strtol(match + 1, NULL, 8);
    

    Note that I incremented the pointer to match by 1 since it begins with a "\\" which strtol will stop on.