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.
This solution has no more copying than necessary. It does require one strlen, so if the directory name retrieval can return the number of bytes copied or if you can precalculate the parent dir string length, you can optimize that away.
void GetFilename(char *pFile)
{
strcpy(pFile, "someFile");
}
void GetParentDir(char *pDir)
{
strcpy(pDir, "/parentdir");
}
int _tmain(int argc, _TCHAR* argv[])
{
char path[1024];
GetParentDir(path);
int dirSize = strlen(path);
path[dirSize] = '/';
GetFilename(path + dirSize + 1);
printf(path);
return 0;
}