Prepending to a string

后端 未结 8 2095
北荒
北荒 2020-12-09 01:49

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.

8条回答
  •  不思量自难忘°
    2020-12-09 02:45

    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 );
    

提交回复
热议问题