Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check whether a string ends with ".csv" in C [duplicate]

Tags:

c

string

How can I check whether a string ends with .csv in C?

I've tried using strlen without any success.

like image 206
ahmet Avatar asked Apr 27 '12 08:04

ahmet


2 Answers

How about:

char *dot = strrchr(str, '.');
if (dot && !strcmp(dot, ".csv"))
    /* ... */
like image 86
cnicutar Avatar answered Oct 06 '22 04:10

cnicutar


The simplest (and most general) form of ThiefMaster's code would be:

int string_ends_with(const char * str, const char * suffix)
{
  int str_len = strlen(str);
  int suffix_len = strlen(suffix);

  return 
    (str_len >= suffix_len) &&
    (0 == strcmp(str + (str_len-suffix_len), suffix));
}
like image 21
MikeW Avatar answered Oct 06 '22 03:10

MikeW