【问题标题】:Get file extension in lowercase in C在C中获取小写的文件扩展名
【发布时间】:2019-06-03 05:20:05
【问题描述】:

我正在尝试在 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]!='\0'){
       if(s[i]>='A' && s[i]<='Z'){
          s[i]=s[i]+32;
       }
       ++i;
    }
}

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

【问题讨论】:

  • return ""(只读常量字符串)用于声称返回非常量 char * 的函数。迟早不会有那么好的结果。估计这会更早。顺便说一句,传递给函数的文字也有同样的问题。两者都是错误的。你不能修改它们。坦率地说,我很惊讶你的编译器没有发出一个大的警告告诉你你正在将 const 数据传递给一个需要非常量的函数。

标签: c pointers file-extension


【解决方案1】:

您的代码正在尝试更改常量字符串"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

【讨论】:

    猜你喜欢
    • 2011-07-15
    • 2019-01-01
    • 1970-01-01
    • 2023-03-02
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    相关资源
    最近更新 更多