Search code examples
cscanfc-stringsformat-specifiersconversion-specifier

What exactly does this format string do when paired with fscanf?


I am looking at some code and came across this line:

fscanf(file, "%*[: ]%16s", dest);

What does the %*[: ]%16s format string specifier do?


Solution

  • This format string

    "%*[: ]%16s"
    

    means that all symbols ':' and ' ' (the symbols placed in the square brackets in the format string) must be skipped in the input stream and then at most 16 characters be read in a character array.

    In the format string the symbol * is assignment-suppressing character.

    Here is a demonstration program. For visibility I am using sscanf instead of fscanf.

    #include <stdio.h>
    
    int main( void ) 
    {
        const char *stream = "::: : : : :::Hello";
        char s[17];
        
        sscanf( stream, "%*[: ]%16s", s );
        
        printf( "\"%s\"\n", s );
    
        return 0;
    }
    

    The program output is

    "Hello"