funtion optimieren
-
hi, kann man folgende funktion noch etwas optimieren?
cu
aufruf: get_subpath("/FOO_0_0/FOO_1_0/FOO_2_0", 2) -> returns FOO_1_0 aufruf: get_subpath("/FOO_0_0/FOO_1_0/FOO_2_0", 0) -> returns / aufruf: get_subpath("/FOO_0_0/FOO_1_0/FOO_2_0", 1) -> returns FOO_0_0 static char *get_subpath(const char *dir, uint32_t depth) { int i = 0; char *pToken; char *str; char *tmp; char *dir_copy; // speicher fuer dir_copy allokieren ... strcpy(dir_copy, dir); // speicher fuer tmp allokieren ... if(dir_copy[0] == '/') { if(strlen(dir_copy) > 0) { strncpy(tmp, dir_copy, 1); } if(i == depth) { Mem_DecRef( dir_copy ); return tmp; } else i++; pToken = strtok(dir_copy, "//"); if (pToken) { strcpy(tmp, pToken); if(i == depth) { Mem_DecRef( dir_copy ); return tmp; } else i++; while ( (pToken = strtok(NULL, "//")) ) { strcpy(tmp, pToken); if(i == depth) { Mem_DecRef( dir_copy ); return tmp; } else i++; } } } /* clean up everything we might have allocated */ free( tmp ); free( dir_copy ); return NULL; }
-
Ka, aber teste auch mal, was passiert, wenn du //FOO_0_0/FOO_1_0/FOO_2_0 oder /FOO_0_0/FOO_1_0/FOO_2_0/ oder /FOO_0_0/FOO_1_0/FOO_2_0// hast -> lösche erst alle überflüssigen /. Bin jetzt doch zu faul, durch den Code zu gehen.
-
konnete auch noch optimiert werden..hmm
set_path("/FOO_0_3/FOO_1_4", 1) -> returns "/FOO_0_3" also gleiches prinzip wie obere funktion...nur halt fullpath!static char *set_path(const char *dir, uint8_t dir_depth) { char *tmp; char *str_tmp; char *dir_copy; unsigned int dir_depth_count = 0; char char_old; // speicher fuer dir_copy allokieren ... // speicher fuer tmp allokieren ... memset(tmp, 0, sizeof(tmp)); strcpy(dir_copy, dir); str_tmp = strstr(dir_copy, "/"); char_old = dir_copy[str_tmp-dir_copy+1]; dir_copy[str_tmp-dir_copy+1] = '\0'; if(dir_depth_count++ == dir_depth) { strcpy(tmp, dir_copy); Mem_DecRef(dir_copy); return tmp; } dir_copy[str_tmp-dir_copy+1] = char_old; while(str_tmp != NULL) { str_tmp = strchr(str_tmp+1, '/'); if(str_tmp != NULL) { dir_copy[str_tmp-dir_copy] = '\0'; if(dir_depth_count++ == dir_depth) { strcpy(tmp, dir_copy); Mem_DecRef(dir_copy); return tmp; } dir_copy[str_tmp-dir_copy] = '/'; } else { if(dir_depth_count++ == dir_depth) { strcpy(tmp, dir_copy); Mem_DecRef(dir_copy); return tmp; } } } free(dir_copy); return 0; }
-
mem_decref?
kein incref?
-
char *get_subpath (char *dir, size_t depth) { static char buff[256]; char *p; if (depth) depth--; else return "/"; strncpy (buff, dir, sizeof(buff)); p = strtok (buff, "/"); while (depth--) p = strtok (0, "/"); return p; }
-
depth is ja auf 256 limitiert bei dir...hm
-
reini_ schrieb:
depth is ja auf 256 limitiert bei dir...hm
nö, der buffer für den inputstring
du kannst ihn ja grösser machen, wenn du willst.
vielleicht gibt es auf deinem system eine definition 'MAX_PATH' oder sowas?