我寫了以下函數將給定的完整路徑分割成目錄,文件名和擴展名。memmove留下垃圾 - C
#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;
}
這適用於GCC的給定輸入。但是,MSVC在extension
變量上留下一些垃圾數據時失敗。我添加了對發生錯誤的地方的評論。我不明白爲什麼memmove
在MSVC上表現不同?我在兩個地方使用了memmove
,奇怪的是第一個工作正常。
任何幫助,將不勝感激。
一邊點:'「/」'在Windows上也是一個有效的目錄分隔符。如果允許用戶提供任意路徑名並使用「/」提供一個,你的代碼將會中斷。可能還需要覆蓋像「C:foo.txt」這樣的文件名,這些文件可能在DOS傳統中仍然有效(指的是驅動器C上當前目錄中的一個名爲「foo.txt」的文件) )。 – 2010-07-08 06:20:47