What is the most efficient way to prepend to a C string, using as little memory as possible?
I am trying to reconstruct the path to a file in a large directory tree.
You can climb to the top of the directory tree keeping the names as you go along, then paste the names together all at once. At least then you aren't doing unnecessary copies by pushing onto the front.
int i = 0;
int j;
char temp*[MAX_DIR_DEPTH], file[LENGTH];
while (some_condition) {
temp[i++] = some_calculation_that_yields_name_of_parent_dir;
}
char *pCurrent = file;
for( j = i-1; j > 0; j-- )
{
strcpy(pCurrent, temp[j]);
pCurrent += strlen(temp[j]);
*pCurrent++ = '\';
}
strcpy(pCurrent, filename);
*pCurrent = 0;