read和write函数原型为
ssize_t read(int fd, void *buf, size_t count);
ssize_t write(int fd, const void *buf, size_t count);
一般对buf的操作都是写入或者读出字符串,由函数原型可以看出buf是一个无类型的指针,指针又是存放地址的,所以buf可以是一个变量的的地址
1、向文件写入整数
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int fd;
int data1 = 100;
int data2 = 0;
fd = open("./file1",O_RDWR);
int n_write = write(fd,&data1,sizeof(int)); //向file1文件写入data1地址指向的内容
lseek(fd,0,SEEK_SET);
int n_read = read(fd,&data2,sizeof(int)); //读出文件描述符的内容到data2
printf("data2:%d\n",data2);
close(fd);
return 0;
}
可以看到成功的向file1写入了整数100,但是打开file1里面并不是100
虽然人看不懂这个,但是电脑可以识别,这个不是代表程序有问题
2、向文件写入结构体
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
struct test{
int a;
char c;
};
int main()
{
int fd;
struct test data1 = {100,'p'};
struct test data2;
fd = open("./file1",O_RDWR);
int n_write = write(fd,&data1,sizeof(struct test));
lseek(fd,0,SEEK_SET);
int n_read = read(fd,&data2,sizeof(struct test));
printf("data2 : %d %c\n",data2.a,data2.c);
close(fd);
return 0;
}
3、向文件写入结构体数组
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
struct test{
int a;
char c;
};
int main()
{
int fd;
struct test data1[2] = {{100,'q'},{200,'w'}};
struct test data2[2];
fd = open("./file1",O_RDWR);
int n_write = write(fd,&data1,sizeof(struct test)*2);
lseek(fd,0,SEEK_SET);
int n_read = read(fd,&data2,sizeof(struct test)*2);
printf("data2 :%d %c\n",data2[0].a,data2[0].c);
printf("data2 :%d %c\n",data2[1].a,data2[1].c);
close(fd);
return 0;
}