Alex Rivera | Logout

Prepending to a string

Asked 2010-02-24T17:45:03.510
34

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.

Here's an idea of what I was doing before:

char temp[LENGTH], file[LENGTH];
file = some_file_name;

while (some_condition) {
    parent_dir = some_calculation_that_yields_name_of_parent_dir;
    sprintf(temp, "%s/%s", parent_dir, file);
    strcpy(file, temp);
}

This seems a bit clunky though.

Any help would be appreciated. Thanks!

Edit
Report

1 Answer

3

sprintf() is generally not 'fast'. Since you know it's pre-pending memmove() twice would probably be preferable for speed.

If you're allocating the strings with malloc() originally you might consider using realloc() to resize the character arrays so they can contain the new string.

   char* p = malloc( size_of_first_string );
   ...
   p = realloc( p, size_of_first_string + size_of_prepended_string + 1 );
   memmove( p + size_of_prepended_string, p, size_of_first_string );
   memmove( p, prepended_string, size_of_prepended_string );
answered 2010-02-24T18:08:33.613

Your Answer