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 could maintain the string starting from the end. Since you seem to know the maxSize already...
So basically if file initially was (foo.txt)
[] [] [] [] [] [f] [o] [o] [.] [t] [x] [t] [\0]
^
|
lastEmpty
Now if you add a parent dir a/ it will look like
[] [] [] [a] [/] [f] [o] [o] [.] [t] [x] [t] [\0]
^
|
lastEmpty
So the code will look something like (there might be bugs, but you get the idea).
char temp[LENGTH], file[LENGTH];
int lastEmpty = put_at_end(some_file_name, file);
// lastEmpty points to right most empty slot
while (some_condition) {
parent_dir = some_calculation_that_yields_name_of_parent_dir;
int len = strlen(parent_dir);
char *tmp = parent_dir + len -1;
while (lastEmpty > 0) {
file[lastEmpty] = *tmp;
lastEmpty --;
tmp--;
}
}
Since I suppose we could expect parent_dir to be small, going over it twice should be ok. If you want to pass around the file string, you can just use file+lastEmpty+1.