[C编程在Linux上]内存结构体与文件之间的转换

内存结构体=>文件

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

const char* fileName = "/home/fnst/temp/dwntest/file.bin";
struct Person{
    char sex;
    int age;
};

int main(){

    /*simulate the comtb in the memory*/
    struct Person person;
    person.sex = 'M';
    person.age = 12;

    /*write memory to the file*/
    FILE *fp = fopen(fileName, "wb");
    fwrite(&person, sizeof(struct Person), 1, fp);
    fclose(fp);

    return 0;
}

 

文件=>内存结构体

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

const char* fileName = "/home/fnst/temp/dwntest/file.bin";
struct Person{
    char sex;
    int age;
};

int main(){

    struct Person person;

    /*Read the file*/
    FILE* fp = fopen(fileName, "rb");
    fread(&person, sizeof(struct Person), 1, fp);
    fclose(fp);

    /*Printf the data*/
    printf("Person.age: %d", person.age);

    return 0;
}
posted @ 2012-04-12 19:06  邵贤军  阅读(358)  评论(0)    收藏  举报