#include <stdio.h>
static inline void absolute_path_clean(char *path, int len)
{
int i;
char *p, *q;
p = path;
for (i=1; i<len; i++)
{
if (path[i] == '/')
{
q = path +i;
if (q == p + 1)
{
// 连续二个/
char *r = q;
while (r < path + len)
{
char *t = r - q + p;
*t = *r;
r++;
}
path[len-(int)(q-p)] = 0;
i = i - 1;
len = len - 1;
q = p;
}
else if ((q == p+2) && (p[1] == '.'))
{
// 本级路径为.
char *r = q;
while (r < path + len)
{
char *t = r - q + p;
*t = *r;
r++;
}
path[len-(int)(q-p)] = 0;
i = i - 2;
len = len - 2;
q = p;
}
else if ((q == p+3) && (p[1] == '.') && (p[2] == '.'))
{
// 本级路径为..
char *r = q;
// 找出p的上一个/
while (p > path)
{
p--;
if (*p == '/')
{
break;
}
}
while (r < path + len)
{
char *t = r - q + p;
*t = *r;
r++;
}
path[len-(int)(q-p)] = 0;
i = i - (int)(q-p);
len = len - (int)(q-p);
q = p;
}
p = q;
}
}
}
int main()
{
char buf[1024] = {0};
char *path = "//home/../../a/./bb";
strcpy(buf, path);
absolute_path_clean(buf, 1024);
printf("before: %s ,after: %s\n", path, buf);
}
08-02
191