Adding a single char to a char pointer.

Hello,

I'm trying to write a method which will return the extension of a file given the file's name, e.g. test.txt should return txt. I'm using C so am limited to char pointers and arrays. Here is the code as I have it:

char* getext(char *file)
{
        char *extension;
        int i, j;

        for(i=strlen(file); i>0; i--)
        {
          if(file == '.') {
                for(j=i; j<strlen(file); j++) {
                        strcat(extension, (const char *) file[j]);
                }
                return extension;
          }
        }
        return extension;
}

I know this could return a null pointer but I'm just trying to get it working before I clean it up. I'm getting this compile warning:

utils.c:106: warning: cast to pointer from integer of different size

Line 106 is the strcat() call. Does somebody have a simple way of adding a single character to a char pointer? I'm not a great C programmer and have never really fully understood the concept of pointers.

Thanks for your help.

I think your making this harder then it needs to be. Check out the index/rindex() functions.

char* getext(char *file)
{
   char *extension = NULL;

   extension = rindex(file,'.');
   // check for NULL here

   // use this to remove the dot
   return ++extension;
}

Or something like:

char* getext(char *file)
{
  int i;

  for(i=strlen(file)-1; i>0; i--)
  {
    if(file == '.') {
        return file+i+1;
    }
  }
  return NULL;
}

Regards

Make sure your files only have one extension with either of these solutions in the event you have files named like

myFile.tar.gz

my solution would work as it reads from the right.

myFile.tar.gz would return gz

Thanks to everybody for your help. I ended up going with frank_rizzo's suggestion and I now have it working. I didn't even know about the rindex() function so that would probably be why I was trying to make it harder for myself than it had to be.