If I pass NULL or some other value to file_from_path() function it will give segmentation fault.
For that need to check the strrchr return value before using that value.
Code:
char *file=strrchr(pathname,'/')+1;
It may return NULL also. so after checking that return value we can use that for our purpose.
Try this code. It works fine.
Code:
char *exten;
char *file_from_path(char *pathname)
{
char *fname = NULL, *file=NULL,*tmp;
int diff;
tmp=strrchr(pathname,'/');
if(tmp)
file=tmp+1;
char *dif ;
if(file && (exten=strrchr(file,'.')) )
{
dif=exten ;
exten++; // Move one step from the null
file[dif-file]='\0';
}
return file ;
}
int main (void)
{
char pathname[] = "hai";
char *fname = file_from_path(pathname);
printf("path: \"%s\"\nfilename: \"%s\"\n", pathname, fname != NULL ? fname:"(null)");
printf("extension:%s\n",exten);
printf("\n");
system("pause");
return 0;
}