一.写入一个整数
具体操作:
int fd;
int data = 100;
int data2 = 0;
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));
运行显示:
read: 100
文件(二进制):
d^@^@^@a^@^@^@e^@^@^@b^@^@^@
~
说明:写入的整数是代码显示的, 二进制的无法识别,所以显示的乱码
二.写入一个结构体
具体操作:
int n_write = write(fd,&data,sizeof(struct Test));
lseek(fd,0,SEEK_SET);//改变光标位置,从头开始
int n_read = read(fd,&data2,sizeof(struct Test));
三.写入一个结构体数组
具体操作:
struct Test data[2] = {{100,'a'},{101,'b'}};
struct Test data2[2];
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);