How to check file extensions in c?

I have been struggling with this for several days now.

I want to create functions that go through the directory, select all files with the * .csv extension and read the data in them.

I created a function that should check every file name that is legal, checking that the line ends with .csv. For this, I want to go to the end of the char * array. I tried this:

 char * point = file_name;
 while (point != "\0"){
    point += 1;
 }

which goes through the char * array without searching and "\ 0".

If i write

*point != "\0"

The compiler warns me that I am comparing and int with char.

I should note that I get the file name using

 dirent->d_name
+3
source share
6 answers

point != "\0" compares a pointer to another pointer that is not what you want.

point char 0. , ,

*point != '\0'; 

. ,

point = file_name + strlen(filename); 

, .csv, -

if((point = strrchr(filename,'.')) != NULL ) {
     if(strcmp(point,".csv") == 0) {
          //ends with csv
      }
  }

EDIT:

+9

, :

while (*point != '\0')
  point++;

, ( ), ( ). , .

, , , . :

int ends_with(const char* name, const char* extension, size_t length)
{
  const char* ldot = strrchr(name, '.');
  if (ldot != NULL)
  {
    if (length == 0)
      length = strlen(extension);
    return strncmp(ldot + 1, extension, length) == 0;
  }
  return 0;
}

, . ends_with ( "test.foo", "foo", 3), 1 , , 0.

, , , .

+7

, . ( , ) ( , JavaScript PHP), "" ++. ( PHP, ).

"a" - - a const char[2]. 'a' - char - a char.

, , , '\0'. "\0", ( ).

+1

, . . . *:

 char * point = file_name;
 while (*point != '\0')
    ++point;
0

, strrchr, :

char * end = strrchr(filename, '.');
if(strcmp(end, ".csv") == 0)
{
    // Yuppee! A CSV file! Let do something with it!
}

( , , .)

0

@unwind, , , name extension. , , const char.

int stringEndsWith(
        char const * const name,
        char const * const extension)
{
    size_t length = 0;
    char* ldot = NULL;
    if (name == NULL) return 0;
    if (extension == NULL) return 0;
    length = strlen(extension);
    if (length == 0) return 0;
    ldot = strrchr(name, extension[0]);
    if (ldot != NULL)
    {
        return (strncmp(ldot, extension, length) == 0);
    }
    return 0;
}
0

Source: https://habr.com/ru/post/1788953/


All Articles