I'm trying to parse an extension out of a list of files of the format 'filename.extension'. However in the cases where filename is blank, I'm getting undesired results.
For example....
sscanf(my_string,"%*[^.].%s",file_ext);
Will properly parse the below
foo.gif such that file_ext = gif
bar.jpg such that file_ext = jpg
However it will fail to parse cases where the prefixed filename is missing. i.e.
.pdf will result in file_ext = NULL
I've tried to use the ? operator after ] to indicate the string may or may not exist; however it's clearly not supported in C. Is there another solution or something I'm overlooking? Thanks!
You can use the standard string function strchr
to determine whether a point is present and then use strcpy
to copy the file extension. For example
char *p = strchr( my_string, '.' );
if ( p != NULL ) strcpy( file_ext, p + 1 );
Or you can use strrchr
that finds the last occurrence of a character.
char *p = strrchr( my_string, '.' );
if ( p != NULL ) strcpy( file_ext, p + 1 );