首先注意ssize_t read(int fd, void *buf, size_t count);第二个参数是地址,定义整数后取地址
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int data = 100;
int data2 = 0;
int fd;
fd = open("./file1",O_RDWR);
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;
}
可以写一个结构体,可以写多个结构体,在此用的结构体数组
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
struct Test
{
int a;
char c;
};
int main()
{
struct Test data[2] = {
{100,'C'},{101,'b'}};
struct Test data2[2];
int fd;
fd = open("./file1",O_RDWR);
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",data2[0].a,data2[0].c);
printf("read:%d,%c\n",data2[1].a,data2[1].c);
close(fd);
return 0;
}