在C中将Struct保存在数据库文件中

时间:2012-03-12 14:42:45

标签: c database struct tree save

我想将结构保存到db文件(或.txt,它仍无关紧要!)但是我遇到了以下问题。我想在结构体中创建结构,如下面的代码。

typedef struct classes cl;
typedef struct attribute a;

struct classes{  \\where "a" is a type of struct
    a hunter;
    a channeler;
    a warrior;
    a rogue; };


struct human{     \\where "cl" is type of struct classes (
cl Borderlands;
cl Shienear;
cl Arafel;
cl Illian;
cl Tear;
cl Tarabon;
cl Andor;
cl TwoRivers;
cl Amandor;
cl Mayene;
cl Murandy;
};

问题是我是否有变量     结构人类数据 我是否必须保存树的所有分支(因为我认为它是我创建的树),或者只是保存根,我是否保存整个结构?

P.S。请原谅我的写作方式,我不是那种编程经验

3 个答案:

答案 0 :(得分:2)

你应该为每个结构制作保存方法:

void save_h(human * h, FILE * stream)
{
    save_cl(h->Borderlands,stream);
    save_cl(h->Shienear,stream);
    save_cl(h->Arafel,stream);
    save_cl(h->Illian,stream);
    save_cl(h->Tear,stream);
    save_cl(h->Tarabon,stream);
    ...
}

void save_cl(classes * cl, FILE * stream)
{
    save_a(cl->hunter,stream);
    save_a(cl->channeler,stream);
    save_a(cl->warrior,stream);
    save_a(cl->rogueon,stream);
    ...
}

void save_a(attribute * a, FILE * stream)
{
    ...
}

答案 1 :(得分:1)

如果你有没有指针的简单结构,固定大小的字段类型,并且不打算将这些数据移动到其他机器上,你可以简单地将整个结构写入二进制文件,因为它在内存中有线性表示。并以同样的方式阅读它。否则,请阅读有关编组和解组数据的信息。如果你不理解这个概念,那么这些代码实际上都没有用。

答案 2 :(得分:0)

我将如何做到这一点:

#define STRUCTFLAG 565719 // some random number

// NOTE: This is based on the idea that sizeof(int) == sizeof(int *). 
// If this is wrong, then make the type of variables such that 
// sizeof(typeof variable) = sizeof(int *).
struct basestruct {
    int flag; // when initialized, this has the value of STRUCTFLAG, so that we know it's a struct
    int size; // total size of the struct, in bytes. set when struct is created.

    // all other variables in the struct are either pointers to other structs or of the primitive type of the size 'int *'.
}

struct mystruct {
    int flag;
    int size;

    struct mystruct2 *variable1;
    struct mystruct3 *variable2;
}

int isStruct(const void *structAddr)
{
    int *casted = (int *) structAddr;
    return casted[0] == STRUCTFLAG;
}
void saveStruct(FILE *file, const void *structaddr)
{
    // make sure it's a struct
    if (isStruct(structaddr))
    {            
        int *casted = (int *) structaddr;
        fprintf(file, "%i\n", casted[0]); // print flag

        casted++; // skip 'flag';

        fprintf(file, "%i\n", casted[0]); // print size
        int numVariables = ((casted[0] / sizeof(int)) - 2);

        casted++;

        for (int i = 0; i < numVariables; i++)
        {
            if (isStruct(casted + i))
            {
                saveStruct(file, casted + i);
            }
            else
            {
                fprintf(file, "%i\n", casted[i]);
            }
        }
    }
    else
    {
        // report error
    }
}

祝你好运阅读它。你只问如何保存它!