Сохранение структуры в файле базы данных в C - PullRequest
1 голос
/ 12 марта 2012

Я хотел бы сохранить структуру в файл базы данных (или .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 ]

2 голосов
/ 12 марта 2012

Вы должны сделать метод сохранения для каждой структуры следующим образом:

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 голос
/ 13 марта 2012

Если у вас есть простые структуры без указателей, типов полей фиксированного размера и вы не планируете перемещать эти данные на другие машины, вы можете просто записать всю структуру в двоичный файл, поскольку он имеет линейное представление в памяти.И прочитайте это так же.В противном случае читайте о маршалинге и демаршалинге данных.Если вы не понимаете эту концепцию, ни один из кодов на самом деле не очень полезен.

0 голосов
/ 12 марта 2012

Вот как бы я это сделал:

#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
    }
}

Удачи, читая это обратно, хотя. Вы только спросили, как его сохранить!

...