c - 如何从 C 中的字符串中去除文件扩展名?

标签 c string replace split

如何从 C 语言中的字符串中去除文件扩展名?

例如,

如果我有带有文件扩展名的文件名

hello.txt

hello.c

hello.java

所有结果都应该只是文件名,不带扩展名

hello

文件扩展名的长度并不重要。

该函数还应该是可移植的并且依赖于系统。

我知道如何使用 strchrstrrchr 获取文件扩展名。我已经在 Bash 和 Python 中完成了此操作,但我从未在 C 中这样做过。

注意:这是一次个人练习,旨在帮助加强我对 C 编程语言的理解。

最佳答案

我不知道有没有最好的方法,但这是一种方法。大概您不想从点文件中删除名称。另外,您可能只想删除从最后一个点到字符串末尾的字符。请注意,在下面的代码中,输入字符串被修改,因此文件名不能是字符串文字,而必须是以 null 结尾的字符数组。

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

void strip_ext(char *);

int main(void)
{
    char filename1[] = "myfile.txt";
    char filename2[] = ".emacs";
    char filename3[] = "anotherfile.";
    char filename4[] = "nodot";
    char filename5[] = "";
    char filename6[] = "dot.dot.dot";

    strip_ext(filename1);
    strip_ext(filename2);
    strip_ext(filename3);
    strip_ext(filename4);
    strip_ext(filename5);
    strip_ext(filename6);

    printf("file1: %s\n", filename1);
    printf("file2: %s\n", filename2);
    printf("file3: %s\n", filename3);
    printf("file4: %s\n", filename4);
    printf("file5: %s\n", filename5);
    printf("file6: %s\n", filename6);

    return 0;
}

void strip_ext(char *fname)
{
    char *end = fname + strlen(fname);

    while (end > fname && *end != '.') {
        --end;
    }

    if (end > fname) {
        *end = '\0';
    }
}

程序输出:

file1: myfile
file2: .emacs
file3: anotherfile
file4: nodot
file5: 
file6: dot.dot

更新

@David C. Rankin指出更复杂的文件路径可能会使事情变得复杂。下面是对 strip_ext() 函数的修改,当遇到正斜杠或反斜杠时,该函数停止查找点,在这种情况下文件名字符串保持不变:

void strip_ext(char *fname)
{
    char *end = fname + strlen(fname);

    while (end > fname && *end != '.' && *end != '\\' && *end != '/') {
        --end;
    }
    if ((end > fname && *end == '.') &&
        (*(end - 1) != '\\' && *(end - 1) != '/')) {
        *end = '\0';
    }  
}

使用相同的测试字符串和附加测试字符串运行此函数:

char filename7[] = "/my.dir/myfile";
char filename8[] = "/dir/.filename";

生成此输出:

file1: myfile
file2: .emacs
file3: anotherfile
file4: nodot
file5: 
file6: dot.dot
file7: /my.dir/myfile
file8: /dir/.filename

关于c - 如何从 C 中的字符串中去除文件扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43163677/

相关文章:

C编程中检查输入是否为数字

Javascript 在 C# 后面的代码中不警告数据库中的字符串变量值,而是警告整型变量,为什么?

regex - 从 R 中的字符串中删除反斜杠

反转句子的c程序

c - strtok 和函数调用

c - Eric Young 的 "crypto/conf/conf.h"中的两圆括号有什么用?

c# - 字符串与字符比较

javascript - JS String 的长度为 n,但只有 n-1 个字符。使用 str = str.slice(0,-1)

mysql - 用于删除列上的部分 URL 的 SQL 语句

SQL替换查询