Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepending to a string

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!

like image 246
Ryan Avatar asked Feb 24 '10 17:02

Ryan


People also ask

How do you prepend to a string in Ruby?

In Ruby, we can use the prepend() method to prepend one string or multiple strings to another string. When we prepend a certain string to another using the prepend method, we get a new string with the latter concatenated with the former.

Can I append to a string in C++?

Append() is a special feature in the string library of C++ to append a string of characters to the other string. This is similar to += or push_back operator with one enhanced feature that it allows to append multiple characters at one time.

How do you add a value to the front of a string?

Use the addition (+) operator to add a string to the beginning and end of another string, e.g. "before" + str + "after" .


1 Answers

Copying can hardly be avoided if you want it in the same memory chunk. If the allocated chunk is large enough you could use memmove to shift the original string by the length of what you want to prepend and then copy that one into the beginning, but I doubt this is less "clunky". It would however save you extra memory (again, granted that the original chunk has enough free space for them both).

Something like this:

#include <stdio.h> #include <string.h> #include <stdlib.h>  void prepend(char* s, const char* t);  /* Prepends t into s. Assumes s has enough space allocated ** for the combined string. */ void prepend(char* s, const char* t) {     size_t len = strlen(t);     memmove(s + len, s, strlen(s) + 1);     memcpy(s, t, len); }  int main() {     char* s = malloc(100);     strcpy(s, "file");     prepend(s, "dir/");      printf("%s\n", s);     return 0; } 
like image 194
Eli Bendersky Avatar answered Sep 19 '22 19:09

Eli Bendersky