#include #include #define MAXSTRLEN 512 int findloc_r(char * str, char c, int start); int findStrLoc(char * str, char* pattern, int i); /* * Given a path (inPath) and current url, convert the path * to an absolute path. * The following are examples * 1. inPath = ./a/b/test.html currentUrl = http://x.y.z/m/n/ * the returned path shoul dbe /m/n/a/b/test.html * 2. inPath = ./a/b/c/.././test.html, currentUrl = http://x.y.z/m/ * the returned path should be /m/a/b/test.html */ char* convertRelPath(char * inPath, char * currentUrl) { char * workBuf = (char*)malloc(MAXSTRLEN); char * base = (char*)malloc(MAXSTRLEN); char * path = (char*)malloc(MAXSTRLEN); char * loc = strstr(currentUrl, "://"); /* locate host */ loc = strstr(loc+3, "/"); /* then the path */ strcpy(path, loc); /* copy the path portion from the currentUrl */ if (inPath == NULL) return path; else if (inPath[0] == '/') /* root path */ strcpy(path, inPath); else strcat(path, inPath); /* attach the inPath to path */ if (path == NULL) return currentUrl; /* collapse all "/./" */ int changed = 0; int i = findStrLoc(path, "/./", 0); while (i >= 0) { changed = 1; strncpy(workBuf, path, i); /* copy the first part */ workBuf[i] = 0; strcat(workBuf, &(path[i+2])); /* then the second part */ strcpy(path, workBuf); i = findStrLoc(path, "/./", 0); } /* collapse all "/../" */ i = findStrLoc(path, "/../", 0); while (i >= 0) { changed = 1; int i2 =findloc_r(path, '/', i-1); if (i2 < 0) i2 = i; strncpy(workBuf, path, i2); /* copy the first part */ workBuf[i2] = 0; strcat(workBuf, &(path[i+3])); /* then the second part */ strcpy(path, workBuf); i = findStrLoc(path, "/../", 0); } return path; } int findloc_r(char * str, char c, int i) { /* find and return the location of 'c' in 'str' in reverse direction */ while (i >= 0 && str[i] != 0 && str[i] != c) { i --; } if (i >= 0 && str[i] == c) return i; else return -1; /* not found */ } int findStrLoc(char * str, char* pattern, int i) { /* find and return the location of 'pattern' in 'str' */ int len = strlen(pattern); int found = -1; while (str[i] != 0 && found == -1) { if (str[i] == pattern[0] && strncmp(&(str[i]), pattern, len) == 0) found = i; i ++; } return found; }