这是我做的一些懒惰的事情,它最大限度地利用了标准库函数(也许你想要这样的东西?):
#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 个字符的扩展。