温馨提示×

C语言序列化与反序列化怎么实现

小亿
86
2024-04-28 14:32:48
栏目: 编程语言

在C语言中,序列化和反序列化是将数据转换为可以存储或传输的格式,以及将存储或传输的数据重新转换为内存中的数据结构的过程。

序列化的实现通常包括将数据转换为字节流,并将字节流写入文件或发送到网络。反序列化则是从文件或网络接收字节流,将其转换为数据结构。

以下是一个简单的示例,演示如何在C语言中实现序列化和反序列化:

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

typedef struct {
    int id;
    char name[50];
    float score;
} Student;

void serialize(Student student, FILE* file) {
    fwrite(&student, sizeof(Student), 1, file);
}

void deserialize(Student* student, FILE* file) {
    fread(student, sizeof(Student), 1, file);
}

int main() {
    Student s1 = {1, "Alice", 95.5};
    Student s2;

    FILE* file = fopen("data.bin", "wb");
    if (file == NULL) {
        fprintf(stderr, "Error opening file\n");
        return 1;
    }

    // Serialize
    serialize(s1, file);
    fclose(file);

    file = fopen("data.bin", "rb");
    if (file == NULL) {
        fprintf(stderr, "Error opening file\n");
        return 1;
    }

    // Deserialize
    deserialize(&s2, file);

    printf("Deserialized student: %d %s %.1f\n", s2.id, s2.name, s2.score);

    fclose(file);

    return 0;
}

在上面的示例中,我们定义了一个名为Student的结构体,包含id、name和score字段。然后实现了一个serialize函数,将Student结构体写入文件,并实现了一个deserialize函数,从文件中读取Student结构体。

在main函数中,我们创建一个Student结构体s1,并将其序列化到文件"date.bin"中。然后从文件中读取数据,并将其反序列化为另一个Student结构体s2,并打印出来。

这只是一个简单的示例,实际应用中可能需要考虑更复杂的数据结构和序列化格式。

0