关于指针:在C中以小写形式获取文件扩展名

Get file extension in lowercase in C

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

我看过以下链接:

  • 在C中获取文件扩展名
  • https://www.includehelp.com/c-programs/c-program-to-convert-string-into-lower-and-upper-case.aspx

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#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\
"
, ext) ;
    stringLwr(ext) ;
    printf("Ext: %s\
"
, 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;
    }
}

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


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

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