直接将结构体的数据存储到文件有很多好处,例如,自带弱加密,节省中间转换的步骤。
本次就做一个小测试,将结构体AAA写入文件hello.txt,然后再将其读出来。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
struct AAA{
int a;
int b;
};
int main(int c,char *v[])
{
int fd;
int ret;
fd = open("hello.txt",O_RDWR|O_CREAT|O_TRUNC);
if(fd < 0){
printf("xixi\n");
return -1;
}
struct AAA a[2] = {{1,2},{3,4}};
write(fd,(char*)a,sizeof(a));
close(fd);
fd = open("hello.txt",O_RDONLY);
if(fd < 0){
printf("heheh\n");
return -1;
}
struct AAA b[2] = {0};
ret = read(fd,(char*)b,sizeof(a));
printf("ret = %d\n",ret);
ret = read(fd,(char*)b,sizeof(a));
printf("ret = %d\n",ret);
ret = read(fd,(char*)b,sizeof(a));
printf("ret = %d\n",ret);
printf("%d\n",b[1].b);
close(fd);
return 0;
}
测试结果:验证成功
sudo ./a.out
4
lkmao@ubuntu:/big/glib/x86/GAsyncQueue$