1

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!

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
jparanich
  • 8,372
  • 4
  • 26
  • 34
  • 3
    `scanf` format strings are *not* regular expressions. You can only use them for a very limited parsing. You better read the whole string, then validate/parse by other means. – Eugene Sh. Jun 09 '21 at 17:42

1 Answers1

1

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 );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335