Simpler newfilenamemcopy

This commit is contained in:
Philippe Teuwen 2019-04-29 22:40:10 +02:00
parent 35ea8e745e
commit 73b6fa7cbc

View file

@ -73,24 +73,19 @@ static char *filenamemcopy(const char *preferredName, const char *suffix) {
static char *newfilenamemcopy(const char *preferredName, const char *suffix) { static char *newfilenamemcopy(const char *preferredName, const char *suffix) {
if (preferredName == NULL) return NULL; if (preferredName == NULL) return NULL;
if (suffix == NULL) return NULL; if (suffix == NULL) return NULL;
char *preferredNameTmp = (char *) calloc(strlen(preferredName) + 1, sizeof(uint8_t)); uint16_t preferredNameLen = strlen(preferredName);
if (preferredNameTmp == NULL) if (str_endswith(preferredName, suffix))
return NULL; preferredNameLen -= strlen(suffix);
strcpy(preferredNameTmp, preferredName); char *fileName = (char *) calloc(preferredNameLen + strlen(suffix) + 1 + 10, sizeof(uint8_t)); // 10: room for filenum to ensure new filename
if (str_endswith(preferredNameTmp, suffix))
preferredNameTmp[strlen(preferredNameTmp) - strlen(suffix)] = '\0';
char *fileName = (char *) calloc(strlen(preferredNameTmp) + strlen(suffix) + 1 + 10, sizeof(uint8_t)); // 10: room for filenum to ensure new filename
if (fileName == NULL) { if (fileName == NULL) {
free(preferredNameTmp);
return NULL; return NULL;
} }
int num = 1; int num = 1;
sprintf(fileName, "%s%s", preferredNameTmp, suffix); sprintf(fileName, "%.*s%s", preferredNameLen, preferredName, suffix);
while (fileExists(fileName)) { while (fileExists(fileName)) {
sprintf(fileName, "%s-%d%s", preferredNameTmp, num, suffix); sprintf(fileName, "%.*s-%d%s", preferredNameLen, preferredName, num, suffix);
num++; num++;
} }
free(preferredNameTmp);
return fileName; return fileName;
} }