1.写一个整数到文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
int fd;
int data = 100;
int data2 = 0;
fd = open("./file2",O_RDWR|O_CREAT|0600);
int n_write = write(fd,&data,sizeof(int));
lseek(fd,0,SEEK_SET);
int n_read = read(fd,&data2,sizeof(int));
printf("read :%d\n",data2);
close(fd);
return 0;
}
执行结果:
![](https://img-blog.csdnimg.cn/img_convert/6bb6d9b790f1282f00b649adff8b7f07.png)
2.写一个结构体数组到文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
struct Test
{
int a;
char b;
};
int main()
{
int fd;
struct Test data[2] = {{100,'c'},{120,'A'}};
struct Test data2[2];
fd = open("./file2",O_RDWR|O_CREAT|0600);
int n_write = write(fd,&data,sizeof(struct Test)*2);
lseek(fd,0,SEEK_SET);
int n_read = read(fd,&data2,sizeof(struct Test )*2);
printf("read :%d, %c\n",data[0].a,data[0].b);
printf("read :%d, %c\n",data[1].a,data[1].b);
close(fd);
return 0;
}
执行结果:
![](https://img-blog.csdnimg.cn/img_convert/531769709ce86fd011336fa5c4eff478.png)