prepending为字符串 [英] Prepending to a string

查看:201
本文介绍了prepending为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最有效的方法prePEND到C字符串,使用尽可能少的内存可能吗?

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

这似乎有点笨重,但。

任何帮助将是AP preciated。谢谢!

Any help would be appreciated. Thanks!

推荐答案

也很难,如果你想在同一个内存块复制避免。如果分配的块是足够大的,你的可能的使用 memmove与来原始字符串由您想prePEND,然后什么长度移位复制一成的开始,但我怀疑这是少了笨重。然而,它会为你节省额外的内存(再次,理所当然地认为原块有他们两个足够的可用空间)。

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

事情是这样的:

#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>


/* 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);
    size_t i;

    memmove(s + len, s, strlen(s) + 1);

    for (i = 0; i < len; ++i)
    {
        s[i] = t[i];
    }
}


int main()
{
    char* s = malloc(100);
    strcpy(s, "file");
    prepend(s, "dir/");

    printf("%s\n", s);
    return 0;
}

这篇关于prepending为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆