I am currently working with a file name and I need to get the name excluding the extension. I have a separate function that determines the extension of the file but can’t find a way how to get the name without the extension.
If I have the file name mylog.txt I only want to be able to get out mylog
I have tried the following
strncpy(fileNameWithoutExt, LogRotateConfiguration->logFileName,
strlen(LogRotateConfiguration->logFileName-strlen(fileExtension)-1));
For some reason though, when I run this I only get minstead of the rest of the file name. I’m never going to know many characters are within the file name or extension so it needs to be worked out what section it needs to get.
So basically, the question how would I get the name of the file without the extension.
Thanks for any help you can provide.
Huh?
Are you seriously subtracting the extension’s length from the pointer you pass to
strlen()? That seems dangerous and weird.Also, you shouldn’t use
strncpy()unless you really need it’s rather quirky semantics. Chances are you don’t, and using it to copy part of a longer string is a pretty good way of failing.A better solution is often to figure out the lengths, and use
memcpy():Note that this also uses
constwhere appropriate, and stores the return value ofstrlen()in variables of the proper type, i.e.size_t.