[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; }

浙公网安备 33010602011771号