简单的结构体序列化

2020-01-30  本文已影响0人  MachinePlay
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
class A{
public:
    int double_data;
    char name[10] = "hello";
};

int main(int argc ,char * argv[]) {
    A *before = new A();
    before->double_data = 100;

    FILE *open_file = fopen(argv[1], "a+");
    if (fwrite(&before, sizeof(A), 1, open_file)!= 1) {
        printf("fwrite error\n");
    }
    A *after = new A();
    printf("dump ok\n");
    fclose(open_file);

    open_file = fopen(argv[1], "r");
    fread(&after, sizeof(A), 1, open_file);
    for (int i = 2; i < 6;++i) {
        printf("%d", after->double_data);
    }
    printf("fread ok\n");
    return 0;
}

缺点在于不能跨系统跨语言
把字节读出来二进制表示即可实现跨语言跨平台

上一篇 下一篇

猜你喜欢

热点阅读