Alan Alan - 4 days ago 6
C Question

Segmentation fault error while trying to get file extension in C

I'm trying to write a function in C, taking in entry a file, that returns 1 if the file extension is png, jpg, etc.

This is what I wrote :

int estImage(struct dirent *fichier)
{
char nomFichier[256];
strncpy (nomFichier, fichier->d_name, 255);

char *dot = strrchr(nomFichier, '.');

char * listeExtensionImage[] = {".png", ".jpg", ".jpeg", ".bmp" };
int len = sizeof(listeExtensionImage)/sizeof(listeExtensionImage[0]);

printf(dot); //Just to test

for (int i=0; i<len; i++)
{
if(!strcmp(listeExtensionImage[i], dot))
return 1;
else
return 0;
}
}


If I put in entry a file that's not a picture (a .c file for example), then it will return 0 with no problem, and the printf(dot) will display ".c".

But, if I try to entry a picture file (.jpg or any other that I listed), I have the message Segmentation fault (core dumped).
Then, I realised that the problem comes from the line :

if(!strcmp(listeExtensionImage[i], dot))


If I delete the for instruction, and everything in-between, then I don't have the error anymore.

But I don't understand why I have this problem, because I have a similary test in the same program, and it works :

int estExecutable(struct dirent *fichier)
{
char nomFichier[256]; // Variable qui contiendra le nom du fichier
strncpy (nomFichier, fichier->d_name, 255);
const char *dot = strrchr(nomFichier, '.');
if(strcmp(dot,".exe")==0)
{
printf(nomFichier);
return 1;
}
else
return 0;
}


This function does work, and I don't see what's the difference between my two functions. Can someone help me please? Thanks!

EDIT : Also tried this version, but got the same error :

int estImage(struct dirent *fichier)
{

char nomFichier[256]; // Variable qui contiendra le nom du fichier
strncpy (nomFichier, fichier->d_name, 255);
char *dot = strrchr(nomFichier, '.');

int retour=0;

if( (!strcmp(dot,".jpg")) || (!strcmp(dot,".png")) || (!strcmp(dot,".jpeg")) || (!strcmp(dot,".bmp")) )
retour = 1;

return retour;
}

Answer

You want this:

int estImage(struct dirent *fichier)
{
    char nomFichier[256];
    strncpy (nomFichier, fichier->d_name, 255);

    char *dot = strrchr(nomFichier, '.');

    if (dot == NULL)
       return 0;  // no extension => it's not an image

    char * listeExtensionImage[] = {".png", ".jpg", ".jpeg", ".bmp" };
    int len = sizeof(listeExtensionImage)/sizeof(listeExtensionImage[0]);

    printf(dot); //Just to test

    for (int i=0; i<len; i++)
    {
        if (strcmp(listeExtensionImage[i], dot) == 0)
            return 1;   // image extension found
    }

    return 0;   // no image extension found
}
Comments