I am trying to remove suffix in next way, but eventually the output is the same as input
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SUFFIX ".doc"
static void removeSuffix(char **outNewFileName, const char *inFileName)
{
*outNewFileName = strdup(inFileName);
outNewFileName[strlen(inFileName) - strlen(SUFFIX)];
}
int main ()
{
char *fileName = "tmp.doc";
char *outnewFileName = NULL;
removeSuffix(&outnewFileName, fileName);
free(outnewFileName);
return 0;
}
for example if fileName is tmp.doc outnewFileName is also tmp.doc
You are very close! Your strlen(inFileName) - strlen(SUFFIX)
expression finds the correct place at which to terminate the new string, but you don't actually do anything with that expression.
To terminate the string at that position, set the value of the char
there to zero (which is the nul
terminator):
static void removeSuffix(char** outNewFileName, const char* inFileName)
{
*outNewFileName = strdup(inFileName);
(*outNewFileName)[strlen(inFileName) - strlen(SUFFIX)] = '\0';
}
In this code, we use (*outNewFileName)
to refer to the new string array, and the offset from that in the square brackets to refer to the actual character that needs to be changed to nul
. (The round brackets are required, because the []
operator has higher precedence that the *
operator.)
Note: As pointed out in the comments, if you had full compiler warnings enabled, you would have seen this (from clang-cl):
warning : expression result unused [-Wunused-value]
Feel free to ask for any further clarification and/or explanation.