dimanche 29 mars 2015

Stripping an extension and directories from a string?

say I have the sring


my/file/file.txt


How would I go about stripping the slashes and the extension to just file? I have google'd my problem, and people have suggested basename, but I'm looking for something that would work on Windows too, any ideas?


Here's what I've tried:



char *rm_ext(char *file) {
char *retstr;
char *lastdot;
if (file == NULL)
return NULL;
if ((retstr = malloc (strlen (file) + 1)) == NULL)
return NULL;
strcpy (retstr, file);
lastdot = strrchr (retstr, '.');
if (lastdot != NULL)
*lastdot = '\0';
return retstr;
}

char *get_file_name(char *path) {
char *s = strrchr(path, '/');
if (!s) return rm_ext(strdup(path));
char *res = strdup(s + 1);
char *res_no_ext = rm_ext(result);
return res_no_ext;
}


It works, but not with D:/ or double slashes, also I think it's giving me memory leaks since there's a bunch of hidden mallocs from strdup.


Aucun commentaire:

Enregistrer un commentaire