在C中以小写形式获取文件扩展名

Get file extension in lowercase in C

我正在尝试在 C 中获取小写文件的文件扩展名。

我看过以下链接:

并将它们合并为以下内容。

#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]!='[=10=]'){
       if(s[i]>='A' && s[i]<='Z'){
          s[i]=s[i]+32;
       }
       ++i;
    }
}

我除了Ext: PDF后面是Ext: pdf。但是,我越来越 Segmentation fault (core dumped) 在第一行之后。我知道这与指针有关,但我无法弄清楚。任何帮助将不胜感激。

您的代码试图更改常量字符串 "test.PDF",这在 C 中是不允许的。您需要将该字符串存储在可写内存中,问题就会消失:

char filename[] = "test.PDF"
char *ext = get_filename_ext(filename) ;
// ext now points to memory inside filename, and
// we can write to it