0

I am trying the get the file extension of a file in lowercase in C.

I have seen the following links:

and have combined them to the following.

#include <stdio.h>
#include <string.h>

char *get_filename_ext(char *filename) ;
void stringLwr(char *s) ;

int main(void) {

    char *ext ;

    ext = get_filename_ext("test.PDF") ;
    printf("Ext: %s\n", ext) ;
    stringLwr(ext) ;
    printf("Ext: %s\n", ext) ;

    return 0;
}

char *get_filename_ext(char *filename) {
    char *dot = strrchr(filename, '.');
    if(!dot || dot == filename) return "";
    return dot + 1;
}

void stringLwr(char *s){
    int i=0;
    while(s[i]!='\0'){
       if(s[i]>='A' && s[i]<='Z'){
          s[i]=s[i]+32;
       }
       ++i;
    }
}

What I except is Ext: PDF followed by Ext: pdf. However, I am getting Segmentation fault (core dumped) after the first line. I know it has to do with the pointer, but I am unable to figure it out. Any help would be appreciated.

ASarkar
  • 469
  • 5
  • 16
  • `return ""` (a read-only constant string) for a function claiming to return non-const `char *`. Sooner or later that's not going to work out too well. Guess this is sooner. Same problem with the literal passed to the function, btw. Both are wrong. You can't modify them. Frankly, I'm surprised your compiler didn't spew a big warning telling you you're passing const data to a function expecting non-const. – WhozCraig Jun 03 '19 at 05:28

1 Answers1

3

Your code is attempting to change a constant string, "test.PDF", which is not allowed in C. You need to store the string in writable memory and the problem will go away:

char filename[] = "test.PDF"
char *ext = get_filename_ext(filename) ;
// ext now points to memory inside filename, and
// we can write to it
user4815162342
  • 141,790
  • 18
  • 296
  • 355