Search code examples
cstringfilenamesfile-extensionstrlen

Changing the extension of a passed filename


My function is passed a filename of the type

char *myFilename;

I want to change the existing extension to ".sav", or if there is no extension, simply add ".sav" to the end of the file. But I need to consider files named such as "myfile.ver1.dat".

Can anyone give me an idea on the best way to achieve this.

I was considering using a function to find the last "." and remove all characters after it and replace them with "sav". or if no "." is found, simple add ".sav" to the end of the string. But not sure how to do it as I get confused by the '\0' part of the string and whether strlen returns the whole string with '\0' or do I need to +1 to the string length after.

I want to eventual end up with a filename to pass to fopen().


Solution

  • May be something like this :

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

    And then the traditional way , remove and rename