#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
struct Test
{
int a;
char c;
};
int main(int argc,char **argv)
{
int fd;
struct Test data[2]={{100,'a'},{101,'b'}};
struct Test data2[2];
fd = open("./file1",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",data2[0].a,data2[0].c);
printf("read %d,%c \n",data2[1].a,data2[1].c);
close(fd);
return 0;
}
运行结果
需要注意的是
ssize_t read(int fd, void *buf, size_t count);
ssize_t write(int fd, const void *buf, size_t count);
中void *buf是无类型的指针,可以设置成任意数据类型的指针,不只是字符串指针。
对于数组a[]而言,&a和a是一样的,都是数组的首地址。