I am trying to create a function that extract the extension from a file name. file_name points to a string containing a file name. The function should store the extension on the file name in the string pointed to by extension. For example, if the file name is “memo.txt”, the function will store “txt” in the string pointed to by extension. If the file name doesn’t have an extension, the function should store an empty string (a single null character) in the string pointed to by extension.
This is what I have:
#include <stdio.h>
void get_extension(char *file_name, char *extension);
int main(){
char *ex;
get_extension("hello.txt", ex);
char *p;
for(p = ex; *p != '\0'; p++){
printf("extension: %c", *p);
}
return 0;
}
void get_extension(char *file_name, char *extension){
char *p;
for (p = file_name; *p != '\0'; p++){
if(*p == '.'){
p++;
while(*p != '\0'){
*extension = *p;
p++;
extension++;
}
} *extension = '\0';
}
}
I keep getting a segmentation fault error and I don't know what is wrong. Can someone help me, please? Thanks!