Question

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().

Was it helpful?

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

OTHER TIPS

Here's something lazy I've whipped up, it makes minimum use of the standard library functions (maybe you'd like something that does?):

#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;
}

And it indeed prints file.bff. Please note that this handles extensions up to 3 chars long.

strlen returns the number of characters in the string but arrays are indexed from 0 so

filename [strlen(filename)]

is the terminating null.

int p;

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

will loop to zero if no extension and stop at the correct spot otherwise.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top