【问题标题】:Changing the extension of a passed filename更改传递的文件名的扩展名
【发布时间】:2013-09-01 19:18:08
【问题描述】:

我的函数被传递了一个类型的文件名

char *myFilename;

我想将现有的扩展名更改为“.sav”,或者如果没有扩展名,只需在文件末尾添加“.sav”即可。但我需要考虑名为“myfile.ver1.dat”的文件。

谁能告诉我实现这一目标的最佳方法。

我正在考虑使用函数来查找最后一个“。”并删除其后的所有字符并用“sav”替换它们。或者如果没有“。”找到了,只需在字符串末尾添加“.sav”即可。但不知道该怎么做,因为我对字符串的 '\0' 部分感到困惑,以及 strlen 是否返回带有 '\0' 的整个字符串,或者我是否需要对字符串长度 +1。

我想最终得到一个文件名以传递给fopen()

【问题讨论】:

    标签: c string filenames file-extension strlen


    【解决方案1】:

    可能是这样的:

    char *ptrFile = strrchr(myFilename, '/');
    ptrFile = (ptrFile) ? myFilename : ptrFile+1;
    
    char *ptrExt = strrchr(ptrFile, '.');
    if (ptrExt != NULL)
        strcpy(ptrExt, ".sav");
    else
        strcat(ptrFile, ".sav");
    

    然后是传统的方式,删除重命名

    【讨论】:

    • 非常感谢。我将此标记为答案,因为它完美地完成了这项工作,并且它还能够处理文件路径为“/folder.1/myfile.data”的情况。我什至没有考虑过这会导致问题,但绝对会。
    【解决方案2】:

    这是我做的一些懒惰的东西,它最大限度地减少了标准库函数的使用(也许你想要这样的东西?):

    #include <stdio.h>
    #include <string.h>
    
    
    void change_type(char* input, char* new_extension, int size)
    {
        char* output = input; // save pointer to input in case we need to append a dot and add at the end of input
        while(*(++input) != '\0') // move pointer to final position
            ;
    
        while(*(--input) != '.' && --size > 0) // start going backwards until we encounter a dot or we go back to the start
            ;
        // if we've encountered a dot, let's replace the extension, otherwise let's append it to the original string
        size == 0 ? strncat(output, new_extension, 4 ) : strncpy(input, new_extension, 4);
    }
    
    int main()
    {
        char input[10] = "file";
    
        change_type(input, ".bff", sizeof(input));
    
        printf("%s\n", input);
    
        return 0;
    }
    

    它确实打印了file.bff。请注意,这可以处理最多 3 个字符的扩展名。

    【讨论】:

      【解决方案3】:

      strlen 返回字符串中的字符数,但数组从 0 开始索引,所以

      文件名 [strlen(文件名)]

      是终止的空值。

      int p;

      for (p = strlen (filename) - 1; (p > 0) && (filename[p] != '.'); p--)

      如果没有扩展,将循环到零,否则在正确的位置停止。

      【讨论】:

      • 为澄清 strlen 的工作原理而欢呼,现在更有意义了。
      猜你喜欢
      • 1970-01-01
      • 2017-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-18
      • 2010-11-25
      • 2020-06-04
      • 1970-01-01
      相关资源
      最近更新 更多