#include #include #include "ostool.h" #include "commun.h" /* Transforme un path absolue en path relatif. Le path abspath sera transform‚ pour devenir relatif refpath. Retourne -1 si l'op‚ration n'est pas possible. relpath contiendra abspath dans ce cas. Retourne 0 si abspath ‚tait directement "sous" refpath. Retourne le nombre de .. requis pour ‚tablir le path relatif. */ export int path_abs2rel ( const char *abspath, const char *refpath, /* Path de r‚f‚rence pour transformation */ char *relpath) { char abspath0[MAXSIZ_PATH]; char refpath0[MAXSIZ_PATH]; int ret = -1; int iter_ret = 0; char recule[MAXSIZ_PATH]; /* Contiendra les ../../.. requis */ int len; recule[0] = '\0'; path_setabs (abspath,abspath0); path_setabs (refpath,refpath0); len = strlen(refpath0); while (1){ if (strcmp(refpath0,abspath0)==0){ ret = iter_ret; strcpy (relpath,recule); break; }else if (strncmp(refpath0,abspath0,len)==0 && path_issep(abspath0[len])){ ret = iter_ret; path_make (recule,abspath0+len+1,relpath); break; }else{ /* Elimine le dernier membre de refpath0 */ char *pt = refpath0 + len; while (pt > refpath0 && !path_issep(*pt)) pt--; /* Plus de membre ?. Ca veut dire, pas de path relatif */ if (pt <= refpath0) break; *pt = '\0'; len = (int)(pt - refpath0); iter_ret++; strcat (recule,".."); path_addback (recule,recule); } } return ret; } /* compose un path de fichier a partir du repertoire et du fichier filepath peut etre egal a path filepath peut etre egal a name Le path est optimis‚ pour ‚liminer les retour en arriŠre etc... name peut etre NULL ou une chaine vide. */ export void path_make (const char *path, const char *name, char *filepath) { if (name == NULL || name[0] == '\0'){ if (path != filepath) strcpy (filepath,path); }else if (path == NULL || path[0] == '\0'){ if (name != filepath) strcpy (filepath,name); }else{ char tempo[MAXSIZ_PATH]; strcpy (tempo,name); if (path_issep(tempo[0])){ path_stripsep(path,filepath); }else{ path_addback (path,filepath); } strcat (filepath,tempo); } path_simplifie(filepath,filepath); } #ifdef TEST static void near tst_make0 (const char *path, const char *fname) { char ret[MAXSIZ_PATH]; path_make (path,fname,ret); printf ("%s + %s -> %s\n",path,fname,ret); } static void near tst_make (const char *path) { tst_make0 (path,"*.*"); tst_make0 (path,"\\*.*"); } int main (int argc, char *argv[]) { static char *tbp[]={ "c:", "c:\\", NULL }; static char *tb[][2]={ "e:/kit/groupe", "e:/kit/groupe/vdi", "e:/kit/groupe", "e:/kit/ombre", "e:/kit/groupe", "e:/kit", "e:/kit/groupe", "e:/bc", "e:/kit/groupe", "d:/kit/ombre", NULL }; int i = 0; while (tbp[i] != NULL){ tst_make (tbp[i]); i++; } i = 0; while (tb[i][0] != NULL){ char refpath[MAXSIZ_PATH]; int ret = path_abs2rel (tb[i][1],tb[i][0],refpath); if (ret == -1){ printf ("*** %s ne peut pas ˆtre relatif … %s\n" ,tb[i][1],tb[i][0]); }else{ printf ("%s relatif … %s -> %s [%d]\n" ,tb[i][1],tb[i][0],refpath,ret); } i++; } } #endif