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://i-blog.csdnimg.cn/blog_migrate/304b4a118c6263440bc01067994dbef5.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://i-blog.csdnimg.cn/blog_migrate/c66ff7c4d77006f356683e5cba3396dc.png)