C -追加字符串直到分配的内存结束



让我们考虑下面这段代码:

int len = 100;
char *buf = (char*)malloc(sizeof(char)*len);
printf("Appended: %sn",struct_to_string(some_struct,buf,len));

有人分配了一定数量的内存,以便用字符串数据填充。问题是从some_struct中获取的字符串数据可以是任意长度。所以我想要实现的是使struct_to_string函数做以下事情:

  1. 不分配任何内存到外部(所以,但必须在函数外部分配,并传递)
  2. 在struct_to_string中,我想做这样的事情:

    char* struct_to_string(const struct type* some_struct, char* buf, int len) {
    //it will be more like pseudo code to show the idea :) 
    
    char var1_name[] = "int l1";
    buf += var1_name + " = " + some_struct->l1; 
    //when l1 is a int or some non char, I need to cast it 
    char var2_name[] = "bool t1";
    buf += var2_name + " = " + some_struct->t1; 
    // buf+= (I mean appending function) should check if there is a place in a buf,
    //if there is not it should fill buf with
    //as many characters as possible (without writting to memory) and stop
    //etc.
    return buf;
    }
    

输出应该像:

Appended: int l1 = 10 bool t1 = 20  //if there was good amount of memory allocated or
ex: Appended: int l1 = 10 bo //if there was not enough memory allocated

总结:

  1. 我需要一个函数(或几个函数),将给定的字符串添加到基本字符串而不覆盖基本字符串;
  2. 当基本字符串内存已满时不执行任何操作
  3. 不能使用c++库

另一个我可以问但现在不是很重要的事情:

  1. 是否有一种方法(在C中)迭代结构变量列表以获得它们的名称,或者至少在没有名称的情况下获得它们的值?(例如遍历结构,例如遍历数组;d)

我通常不使用C,但现在我有义务使用,所以我有非常基本的知识。(对不起我的英语)

编辑:

解决这个问题的好方法如下:stackoverflow.com/a/2674354/2630520

我想说你所需要的只是在string.h头文件中定义的标准strncat函数。

关于"遍历结构变量列表"部分,我不太确定你的意思。如果你谈论的是在结构体的成员上迭代,一个简短的回答是:你不能免费自省C结构体。

您需要事先知道您使用的结构类型,以便编译器知道在内存中的偏移量,它可以找到您的结构的每个成员。否则,它只是一个字节数组。

如果我说得不够清楚或者你想要更多的细节,可以问我。好运。

基本上我是这样做的:stackoverflow.com/a/2674354/2630520

int struct_to_string(const struct struct_type* struct_var, char* buf, const int len)
{
    unsigned int length = 0;
    unsigned int i;
    length += snprintf(buf+length, len-length, "v0[%d]",  struct_var->v0);
    length += other_struct_to_string(struct_var->sub, buf+length, len-length);
    length += snprintf(buf+length, len-length, "v2[%d]", struct_var->v2);
    length += snprintf(buf+length, len-length, "v3[%d]", struct_var->v3);
    ....
    return length;
}

snprintf尽可能多地写,并丢弃所有剩下的东西,所以这正是我想要的。

最新更新