1.写一个整数到文件
#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 fd;
int data = 100;
int data2 = 0;
fd = open("./file1",O_RDWR);
write(fd,&data,sizeof(int)); // ssize_t write(int fd, const void *buf, size_t count); 因为write函数的第二个参数是一个无类型的指针,只要是一个指针即可,指针=地址
lseek(fd,0,SEEK_SET);
read(fd,&data2,sizeof(int)); // ssize_t read(int fd, void *buf, size_t count); read函数的第二个参数也是一个无类型的指针
printf("read %d\n",data2);
close(fd);
return 0;
}
2.写结构体数组一个到文件
#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()
{
int fd;
struct Test data[2] = {{100,'a'},{101,'b'}};
struct Test data2[2];
fd = open("./file1",O_RDWR);
write(fd,&data,sizeof(struct Test) * 2);
lseek(fd,0,SEEK_SET);
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;
}