I wrote the following function to split the given full path into directory, filename and extension.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct path_info {
char *directory;
char *filename;
char *extension;
};
#ifdef WIN32
const char directory_separator[] = "\\";
#else
const char directory_separator[] = "/";
#endif
struct path_info* splitpath(const char *full_path)
{
size_t length = strlen(full_path);
struct path_info *p = (struct path_info*) malloc(sizeof(struct path_info) + length + 3); /* Extra space for padding and shifting */
if(p)
{
char *path = (char *) &p[1]; /* copy of the path */
char *end = &path[length + 1];
char *extension;
char *last_separator;
/* copy the path */
strcpy(path, full_path);
*end = '\0';
p->directory = end;
p->extension = end;
p->filename = path;
last_separator = strrchr(path, directory_separator[0]); /* Finding the last directory separator */
if(last_separator) {
memmove(last_separator + 1, last_separator, strlen(last_separator)); /* inserting a directory separator where null terminator will be inserted */
p->directory = path;
*(++last_separator) = '\0'; /* Truncate the directory path */
p->filename = ++last_separator; /* Taking the remaining as file name */
}
/* Finding the extension starts from second character. This allows handling filenames
starts with '.' like '.emacs'.*/
extension = strrchr(&p->filename[1], '.');
if(extension) {
/* shifting the bytes to preserve the extension */
memmove(extension + 1, extension, strlen(extension)); /* problem happens here */
p->extension = extension + 1;
*extension = '\0'; /* Truncates the file name */
}
}
return p;
}
int main(void)
{
struct path_info *p = splitpath("C:\\my documents\\some.txt");
printf("Directory : %s\n", p->directory);
printf("Filename : %s\n", p->filename);
printf("Extension : %s\n", p->extension);
return 0;
}
This works well for the given input on GCC. But it fails on MSVC leaving some garbage data on extension
variable. I have added a comment on the place where things go wrong. I am not understanding why memmove
is behaving differently on MSVC? I have used memmove
in two places and strange part is that the first one works fine.
Any help would be appreciated.